如何在给定的日期时间运行javascript函数

时间:2015-05-06 10:29:54

标签: javascript php datetime

我想在给定的日期/时间只运行一次特定的javascript function。 例如,我在php中有一个日期时间变量,如下所示。

  $date = "May 7, 2015 17:08:43";

我有一些像

这样的功能
 function some_function()
 {
   .....
   .....
 } 

如何在给定的日期时间May 7, 2015 17:08:43上运行此功能一次。

我尝试了这个,但它无法正常工作。

var date = "<?php echo date('n/j/Y/H:i', strtotime($date));?>";
var myDate = new Date();
var current_date =  (myDate.getMonth()+1)  + "/" + myDate.getDate() + "/" + myDate.getFullYear()+ "/"+ myDate.getHours() + ":" + myDate.getMinutes();
var interval = setInterval(function() { 
    if(date==current_date)
    {
       some_function();           

    }

}, 4000);
clearInterval(interval);

这有什么好的技巧吗?

6 个答案:

答案 0 :(得分:1)

计算服务器端的秒数
使用setTimeout(function(){ some_function(); }, nbreOfSeconds);

setInterval()将按指定的时间间隔评估您的表达式

答案 1 :(得分:1)

您可以使用此javascript方法。将您的给定时间转换为毫秒。

setInterval(function(){ alert("Hello"); }, 3000);

答案 2 :(得分:1)

我想,你可以这样做:

setInterval(function() {
    var myDate = new Date();
    $date = "May 06 2015 13:50:40";
    var reg = new RegExp('\(' + $date.replace(/\s/g, "\\s") + '\)', 'g');
    console.log(myDate)
    if ( myDate.toString().match($date) ) {
        do_something();
    }
}, 1000);

这里是演示:http://jsfiddle.net/pj1248xq/

注意:您需要根据要执行function

的实际日期更改日期

答案 3 :(得分:1)

你必须使用 setTimeout 功能而不是 setInterval ,因为@Halayem说 因为 setTimeout 执行

setInterval 执行然后等待期间(nbreOfSeconds)然后再次循环

好的,你可以使用Jquery(简单选项)进行ajax调用,并在服务器端语言中检查日期 然后返回一个json状态对象,例如

这是一个简单的例子:

check_date.php内容(此文件用于检查日期):

public class GlobalTouchService extends Service implements OnTouchListener{

    private String TAG = this.getClass().getSimpleName();
    // window manager
    private WindowManager mWindowManager;
    // linear layout will use to detect touch event
    private LinearLayout touchLayout;
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        // create linear layout
        touchLayout = new LinearLayout(this);
        // set layout width 30 px and height is equal to full screen
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        touchLayout.setLayoutParams(lp);
        // set color if you want layout visible on screen
        //touchLayout.setBackgroundColor(Color.CYAN);
        // set on touch listener
        touchLayout.setOnTouchListener(this);

        // fetch window manager object
        mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        // set layout parameter of window manager
        WindowManager.LayoutParams mParams = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT, // width is equal to full screen
                WindowManager.LayoutParams.MATCH_PARENT, // height is equal to full screen
                WindowManager.LayoutParams.TYPE_PHONE, // Type Phone, These are non-application windows providing user interaction with the phone (in particular incoming calls).
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, // this window won't ever get key input focus
                PixelFormat.TRANSLUCENT);
        mParams.gravity = Gravity.LEFT | Gravity.TOP;
        Log.i(TAG, "add View");

        mWindowManager.addView(touchLayout, mParams);

    }


    @Override
    public void onDestroy() {
        if(mWindowManager != null) {
            if(touchLayout != null) mWindowManager.removeView(touchLayout);
        }
        super.onDestroy();
    }

    public void showAlert(View view) {
        AlertDialog.Builder myAlertBuilder = new AlertDialog.Builder(this);
        myAlertBuilder.setMessage(getString(R.string.alertMessage))
                .setTitle(getString(R.string.alertTitle))
                .setPositiveButton(getString(R.string.alertPositiveChoice), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setNegativeButton(getString(R.string.alertNegativeChoice), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        onDestroy();
                    }
                });
        AlertDialog myAlert = myAlertBuilder.create();
        myAlert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        myAlert.show();
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        //if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_UP)
        //    Log.i(TAG, "Action :" + event.getAction() + "\t X :" + event.getRawX() + "\t Y :" + event.getRawY());
        ////////////////////
        View myView = null;
        //showAlert(myView);
        ///////////////////////
        return false;
    }
}

这是您的JavaScript代码: 当然你应该首先加载jquery

<?php
   $date = date('n/j/Y/H:i', strtotime($date));
   if($date == 'your wanted date'){
      return json_encode(array('status'=>1));
   }else{
      return json_encode(array('status'=>0));
   }
?>

答案 4 :(得分:1)

function runAt (cbk, timestamp) {
    if (
        ! (timestamp instanceof Date)
        || isNaN (timestamp.getTime())
    ) throw "timestamp should be a valid Date object";
    var ms = timestamp - (new Date()).getTime();
    if (ms < 0) throw "Too late!!";
    setTimeout(cbk, ms);
};

您可以“随时”对其进行测试:

runAt(function(){console.log("Hello!!");}, new Date(new Date().getTime() + 5000));

答案 5 :(得分:1)

github

上有一个对此有用的小型库
  

原生setTimeout函数仅限于INT32(2147483647毫秒或大约24.8天)。该库可以设置超时,几乎无限延迟。

一旦你包含了库,就可以像这样设置超时:

// extra zeros need to get the time in milliseconds (as in JavaScript)
var date = <?php echo strtotime($date);?>000;
var id = timeout.set(some_function, date);

function some_function()
{
    // do some cool stuff
    timeout.clear(id);
}