2016-08-03 186 views
-2

目标是区分两个日期。DateTime比较两个日期

我有一个DateTime对象存储在我的数据库表时间戳列下。我使用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变量现在去的DateTime对象我这样做$result[0][timestamp]

所以,现在我已经检索到的行插入到我的数据库,我需要另一个日期的当前时间的日期检索实际数据我根据这个documentation

这样做$date1 = $result->format('Y-m-d H:i:s');

即:根据本documentation

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

DIFF这给了我这个错误:

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

任何想法,为什么我收到此错误消息看起来像正在做的事情的权利根据码头的方式。也许有另一种方式做差异两个日期OPP的方式。

UPDATE:

好了,所以是的,如果我用$date1 = $result->format('Y-m-d H:i:s');它不再是一个对象的一个​​拨动式它是真实的。

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

$测试= $ result-> DIFF(新的DateTime()); var_dump($ test);

返回DateInterval对象但我做什么了吧:

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) 

我需要什么,如果日期1 diff来DATE2在> 30多分钟,我要采取一些行动。

+0

'$ result-> DIFF($ DATE2)' –

回答

2

这是因为method format返回字符串,但不是对象。尝试使用:

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

$date1现在是没有的格式()方法的字符串。

试试这个: -

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

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

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

0

对于不知道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 
    } 
} 
+0

@Tomazi如果我的回答您的满足问题,请让你的问题从没有答案的问题列表中删除它颁发的绿色的勾。如果仍有问题未解决,请解释,我会尽力提供帮助。 – mickmackusa