检查DateTime始终返回日期

时间:2017-04-30 15:15:06

标签: php datetime timestamp

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';
}

2 个答案:

答案 0 :(得分: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)

尝试使用纪元秒:

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