2012-09-13 207 views
1

我已经看过this的问题,而是时间的格式是不同的PHP的日期和时间比较

我有以下日期格式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()函数。如果您使用这些方法中的任何一种,并且仍然收到此警告,则很可能是拼写错误的时区标识符。我们选择 '美国/纽约' 的 'EDT/-4.0/DST',而不是在/Users/xxxxx/Desktop/xxxx/xxxx/xxxx.php在线26

编辑:

我已经加入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'); 
    } 

作品没有警告,谢谢大家

+0

我编辑过问题 –

+2

那么......你是否调用了'date_default_timezone_set()'函数呢? – verdesmarald

+0

另一方面,如果您比较'strtotime($ pubDate)'到'strtotime(' - 10分钟')'',则会更容易... ... – Havelock

回答

2

使用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'); 
} 

你可以玩弄它,看看它在this demo工作。

+0

+1 '日期时间',而不是旧的'日期'和'时间'功能 – Havelock

+0

'new DateTime('Tue,11 Sep 2012 17:38:09 GMT')'也适用。 – Florent

+0

Florent,谢谢你的提示。我通常避免构造函数,我不知道为什么。感谢Havelock,DateTime类是一个大多未被发现的宝石。 – nickb

1

使用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'); 
2

你可以比较两个datetime对象。

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

if ($myTime >= $nowLessTenMinutes); 
+1

这个答案更多PHP 5.3风格 – Maks3w

+0

这个工作怎么样,'if'的参数是'integer> = object'。按照预期,它会失败,并且注意:DateTime类的对象不能被转换为int。 – nickb

+0

$ myTime是一个DateTime对象。我省略了如何从字符串传递到DateTime。我认为我们不应该给出完整的答案和暗示 – Maks3w

0

我有同样的问题,如果您使用的甲基苯丙胺或类似的事情就会很复杂变化的php.ini试图在你的PHP文件的顶部添加date_default_timezone_set('America/New_York');

然后在这个线程上的其他大部分答案应该工作。