日期时间比较两个日期


DateTime compare two dates

目标是区分两个日期。

我在时间戳列下的数据库表中存储了一个日期时间对象。我使用 Doctrine 来检索日期,一旦从我的数据库中检索到日期,它看起来像这样 var_dump ;

    array(1) {
  [0]=>
  array(1) {
    ["timestamp"]=>
    object(DateTime)#321 (3) {
      ["date"]=>
      string(26) "2016-08-03 11:03:36.000000"
      ["timezone_type"]=>
      int(3)
      ["timezone"]=>
      string(13) "Europe/London"
    }
  }
}

检索到的对象现在被分配给一个$result变量,以访问我$result[0][timestamp]执行的DateTime对象。

为了检索实际数据,我根据本文档$date1 = $result->format('Y-m-d H:i:s');做了这个

因此,现在我已经检索了将一行插入数据库的日期,我需要另一个截至当前时间的日期。

即:

$date1 = $result->format('Y-m-d H:i:s');
$date2 = new DateTime();
$test = $date1->diff($date2);

根据本文档的差异

这给了我这个错误:

Error: Call to a member function diff() on a non-object

任何知道为什么我收到此错误消息看起来像是根据码头以正确的方式做事。也许还有另一种方法可以区分两个日期 OPP 方式。

更新:

好的,是的,如果我使用它$date1 = $result->format('Y-m-d H:i:s');它不再是一个对象,它是一个搅拌,这是真的。

所以现在我的代码看起来像这样:

$test = $result->diff(new DateTime(((;var_dump($test(;

它返回日期间隔对象,但我该从中得到什么:

object(DateInterval)#317 (15) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(0)
  ["d"]=>
  int(0)
  ["h"]=>
  int(1)
  ["i"]=>
  int(27)
  ["s"]=>
  int(5)
  ["weekday"]=>
  int(0)
  ["weekday_behavior"]=>
  int(0)
  ["first_last_day_of"]=>
  int(0)
  ["invert"]=>
  int(0)
  ["days"]=>
  int(0)
  ["special_type"]=>
  int(0)
  ["special_amount"]=>
  int(0)

如果 Date1 与 Date2 的差异>超过 30 分钟,我需要什么,我想采取一些行动。

这是因为方法格式返回字符串,但不返回对象。尝试使用:

$test = $result->diff(new DateTime());
$date1 = $result->format('Y-m-d H:i:s');

$date1现在是一个没有 format(( 方法的字符串。

试试这个:-

$date1 = $result->format('Y-m-d H:i:s');
$date2 = new DateTime();
$test = $result->diff($date2);

在你做$date1 = $result->format('Y-m-d H:i:s');之后。 $date1不再是DateTime对象,而是日期和时间的字符串表示形式。

因此,请跳过此行。不要格式化,然后检查差异。这将给你一个DateTimeInterval对象。

对于任何不知道 diff(( 做什么的人来说,它会比较两个日期并返回差值——但不太可能是其他减法方法,diff(( 从不返回负值。 第一个日期是大于还是小于第二个日期并不重要。

现在,如果这种情况不关心,下一步是访问 DateInterval 对象中的必要值。

$diff=(array)$date1->diff($date2);      // calculate the difference and cast as an array
$labels=array("y"=>"year","m"=>"month","d"=>"day","h"=>"hour","i"=>"minute");
// filter the $diff array to only include the desired elements and loop
foreach(array_intersect_key($diff,$labels) as $k=>$v){
    if(($k!="i" && $v>0) || $v>30){
        // $labels[$k] = $v > 30 minutes, take some action
    }
}