Php日期和时间比较


Php Date and Time Comparision

我看过这个问题,但时间格式与不同

我有以下日期格式Tue, 11 Sep 2012 17:38:09 GMT$pubDate变量中

我想将$pubDate与当前日期和时间进行比较,看看Tue, 11 Sep 2012 17:38:09 GMT是否在最后10分钟内

编辑:

我试过

//get current time
                strtotime($pubDate);
                time() - strtotime($pubDate);
                if((time()-(60*10)) < strtotime($pubDate)){
                    //if true increase badge by one
                    $badge = $badge + 1;
                }

它发出警告:依赖系统的时区设置是不安全的。需要使用date.timezone设置或date_default_timezone_set()函数。如果您使用了其中任何一种方法,但仍然收到此警告,则很可能是您拼错了时区标识符。我们在第26行的/Users/xxxxx/Desktop/xxxxx/xxxx/xxxx.php中选择了"America/New_York"作为"EDT/-4.0/DST"

编辑:

我已经将date_default_timezone_set('America/New_York');行添加到我的php中,现在是

$inDate  = DateTime::createFromFormat( $format, $pubDate);
    $postDate = new DateTime();
    $diff = $inDate->diff( $postDate);
    // If the total number of days is > 0, or the number of hours > 0, or the number of minutes > 10, then its an invalid timestamp.
    if( $diff->format( '%a') > 0 || $diff->format( '%h') > 0 || $diff->format( '%i') > 10) {
     die( 'The timestamps differ by more than 10 minutes');
    }

在没有警告的情况下工作,感谢大家

使用DateTime进行比较:

$format = 'D, d M Y H:i:s O';
$tz = new DateTimeZone( 'America/New_York');
// Create two date objects from the time strings
$pubDate  = DateTime::createFromFormat( $format, 'Tue, 11 Sep 2012 17:38:09 GMT', $tz);
$postDate = DateTime::createFromFormat( $format, 'Tue, 11 Sep 2012 17:38:09 GMT', $tz);
// Compute the difference between the two timestamps
$diff = $pubDate->diff( $postDate);
// If the total number of days is > 0, or the number of hours > 0, or the number of minutes > 10, then its an invalid timestamp.
if( $diff->format( '%a') > 0 || $diff->format( '%h') > 0 || $diff->format( '%i') > 10) {
    die( 'The timestamps differ by more than 10 minutes');
}

你可以在这个演示中使用它并看到它的工作。

您可以比较两个DateTime对象。

$nowLessTenMinutes = new DateTime();
$nowLessTenMinutes->sub(new DateInterval('PT10M')); // Sub 10 minutes
if ($myTime >= $nowLessTenMinutes);

使用DateTime::diff()计算差值:

$input = new DateTime( 'Tue, 11 Sep 2012 17:38:09 GMT' );
$now = new DateTime();
/* calculate differences */
$diff = $input->diff( $now );
echo $diff->format( '%H:%I:%S' );

我也遇到了同样的问题,如果您正在使用MAMP或类似的东西,那么更改php.ini会很复杂。请尝试在您的php文件上添加date_default_timezone_set('America/New_York');

那么这个线程上的大多数其他答案应该都有效。