2017-04-30 58 views
1

attempting to compare two dates,看它是否是在过去或未来检查日期时间总是返回日期在未来

但即使想到了“DateToCheck”是在过去,它总是返回“未来”。如果日期是为未来设定的,它也将在未来返回。

我用这个SO question作为检查的入门书。

<?php 
date_default_timezone_set('UTC'); 
define("TIMESTAMP_FORMAT", "Y-m-d G:i:s"); 

$aString = "2017-03-01 23:11:16"; 
echo "String to convert: ". $aString ."\r\n"; 

$currentTime = date(TIMESTAMP_FORMAT); 
echo "Current Time: ". $currentTime."\r\n"; 

$dateToCheck = new DateTime($aString); 
echo "Date To Check: ". $dateToCheck->format(TIMESTAMP_FORMAT)."\r\n"; 

if($dateToCheck < $currentTime) { 
    echo 'Date is in the past'; 
} else { 
    echo 'Date is in the future'; 
} 
+0

首先,检查服务器时间 – 4EACH

回答

1

确保服务器日期是正确的,那么你可以使用:

if (new DateTime() > new DateTime("2017-03-01 23:11:16")) { 
    # date is in the past 
}else{ 
    # date is in the future 
} 
+1

这工作,但为什么你的版本在我没有的时候工作?对我来说,它们看起来基本上是一回事。 –

+0

我认为它与'$ currentTime = date(TIMESTAMP_FORMAT);'这不是一个日期时间对象。 –

0

尝试使用纪元秒:

if($dateToCheck->format('U') < $currentTime->format('U')) { 
    echo 'Date is in the past'; 
} else { 
    echo 'Date is in the future'; 
} 
相关问题