2014-06-17 88 views
-3

我想比較給定日期是早於當前日期。 IF聲明'日期在未來'的結果。有人能告訴我爲什麼PHP在IF語句中給出了錯誤的結果嗎?PHP無法比較日期

這裏是我使用

$date='17/06/2013'; 
$currentDate = date("d/m/Y"); 

if(strtotime($date) < strtotime($currentDate)) { 
echo 'date is in the past'; 
} 
else{ 
echo 'date is in the future'; 
} 

回答

4

您的日期格式代碼無效。從手動(重點煤礦):在第m

日期/ d/y或DMY格式通過查看在各個組件之間的分離器消除歧義:如果分離器是斜線(/),則美國m/d/y假設爲;而如果分隔符是破折號( - )或點(。),則假定歐洲的d-m-y格式。

如果你打算使用這種格式,你需要明確告訴PHP該日期的格式。使用DateTime::createFromFormat()來消除日期格式的歧義。此外,datetime對象是可比的,這使得代碼更易讀(他們也處理的時區和夏令時間,這strtotime()不做):

$date = DateTime::createFromFormat('d/m/Y', '17/06/2013'); 
$currentDate = new DateTime(); 

if($date < $currentDate) { 
echo 'date is in the past'; 
} 
else{ 
echo 'date is in the future'; 
} 
0

嘗試更換(/)(-)需要通過正確格式的strtotime檢測正確的日期,以便正確的方法是寫日期-(DASH)

$date=str_replace('/', '-', '17/06/2013'); 
$currentDate = date("d-m-Y"); 
if(strtotime($date) < strtotime($currentDate)) { 
    echo 'date is in the past'; 
} 
else{ 
    echo 'date is in the future'; 
} 
1

xkcd
> xkcd

strtotime無法解析您的日期字符串。 false不小於自身,所以日期是「未來」。

嘗試使用正確的方式寫數字日期;)