【问题标题】:Compare a DateTime object against another in PHP 5.3在 PHP 5.3 中将 DateTime 对象与另一个对象进行比较
【发布时间】:2011-12-10 00:17:50
【问题描述】:

好的,我正在制作一个基于文本的在线游戏,但我现在卡在完成时:

function....

    // I can't get this script to execute when I know the time has passed.

    $now = new DateTime("now", new DateTimeZone('UTC'));
    $row_date = new DateTime($row["due_date"], new DateTimeZone('UTC'));

    if ($row_date->format('Y-m-d H:i:s') <= $now->format('Y-m-d H:i:s')) 
    {
        mysql_query(".....")VALUES ("....")or die(mysql_error());
        mysql_query("DELETE FROM ......")or die(mysql_error());
    }
    else 
    {
        // The time has not come yet.
    }

这段代码将使用 jQuery 的 setInterval 每 10 秒执行一次。

【问题讨论】:

  • 对于新的DateTime 对象,默认时区是UTC,不是吗? (因此您不必也传递 DateTimeZone 对象,但请确保。)

标签: php datetime compare


【解决方案1】:

DateTime 可以比较

if ($row_date <= new DateTime) { /* Do something */ }

【讨论】:

  • 我已经尝试过这种方法它不起作用.....我必须先像这样格式化数据 $row_date->format('Y-m-d H:i:s') 2011-12-10 00:33:06 ..... 没有任何效果!!!!
  • 不,就像我写的:不format()$a = new DateTime('2011-12-09 16:23:01'); var_dump($a &lt;= new DateTime); /* bool(true) */
  • +1 提醒我当我第一次意识到我不需要使用format() 时是多么的棒:)
  • 可比?这是技术术语吗? =) PHP 手册对 DateTime 对象 IMO 非常详细和清晰。
【解决方案2】:

将其转换为 unix 时间戳。完美满足您的任何需求。 您可以使用时间戳轻松对时间进行排序,并找出先发生的事件。

$ts=strtotime($date);

【讨论】:

    【解决方案3】:

    您可以避免转换为 DateTime 类并使用seconds since Epoch 值进行任何日期比较。你的代码应该是这样的:

    date_default_timezone_set('UTC');
    $row_date = strtotime($row["due_date"]);
    if ($row_date <= time()) { // The time has come
        mysql_query(".....") VALUES ("....") or die(mysql_error());
        mysql_query("DELETE FROM ......") or die(mysql_error());
    }
    else {
        // The time has not come yet.
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 2013-11-15
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      • 2018-01-12
      • 1970-01-01
      相关资源
      最近更新 更多