2016-08-03 181 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