2011-09-13 73 views
1

我有一個日期字符串像這樣︰2010-9-30在我的$ date_string變量。在PHP中的日期比較行爲不可預知

當我比較字符串這樣的:

if (date('Y-m-d', strtotime("+20 days", $date_string))) 
{ 
    // it returns true for all dates 
} 

的比較是適用於所有日期,甚至是從昨天開始,這是不是20天前。任何想法爲什麼可能會發生?

謝謝!

+1

errr我在代碼中看不到任何比較結果。你基本上說'如果($ some_date_string){做點什麼}' – dqhendricks

回答

1

它以(例如)2000-01-01的字符串格式返回日期,當轉換爲布爾值時,該日期爲true

相反,檢查此:

if (time() > strtotime("+20 days", $date_string)) // Returns true if $date_string was in the last 20 days, or is in the future 

很顯然,如果你想日期只有20多天,就翻轉><

3

您還沒有日期間進行任何比較。相反,您正在測試是否可以成功將作爲第二個參數提供的日期轉換爲strtotime()爲有效日期。結果總是如此,因爲每個日期在將來有20天的有效日期。

換句話說,如果date()返回真值,則您的條件爲TRUE。它將始終返回真實值,除非您在其第二個參數中傳遞了無效時間戳(例如,2月42日)

如果要將該date()調用的輸出與另一個日期字符串進行比較,則需要if()內附加一個操作數:

if ('2011-09-02' == date('Y-m-d', strtotime("+20 days", $date_string))) { 

}