2012-04-17 164 views
3

我有一个保存过去时间戳的DateTime对象。PHP:检查DateTime是否过期

我现在想检查此DateTime是否比例如48小时更早。

我怎样才能合成它们最好?

问候

编辑: 嗨,

感谢您的帮助。 继承人的帮手方法。 任何命名建议?

protected function checkTemporalValidity(UserInterface $user, $hours) 
{ 
    $confirmationRequestedAt = $user->getConfirmationTokenRequestedAt(); 
    $confirmationExpiredAt = new \DateTime('-48hours'); 

    $timeDifference = $confirmationRequestedAt->diff($confirmationExpiredAt); 

    if ($timeDifference->hours > $hours) { 
     return false; 
    } 

    return true; 
} 
+1

'isExpired()'? :) – 2012-04-17 19:59:27

+0

谢谢:)让我们看看我使用var名称做什么 – bodokaiser 2012-04-17 20:02:18

+0

它的格式与'date()'稍有不同,请查看[DateInterval :: format()](http://www.php.net/手动/ EN/dateinterval.format.php)。但是要注意'DateInterval'中没有像'hours'这样的成员变量。请注意文档:) – 2012-04-17 20:06:47

回答

4
$a = new DateTime(); 
$b = new DateTime('-3days'); 

$diff = $a->diff($b); 

if ($diff->days >= 2) { 
    echo 'At least 2 days old'; 
} 

我使用$ a和$ b作'测试'的目的。 DateTime::diff返回DateInterval object,该成员变量days返回实际的日差。

+0

更好的使用(浮动)$ diff-> format('%R%a');而不是$ diff->天 – bleuscyther 2014-10-09 20:56:48

0

我知道这个答案是有点晚,但也许它可以帮助别人:

/** 
* Checks if the elapsed time between $startDate and now, is bigger 
* than a given period. This is useful to check an expiry-date. 
* @param DateTime $startDate The moment the time measurement begins. 
* @param DateInterval $validFor The period, the action/token may be used. 
* @return bool Returns true if the action/token expired, otherwise false. 
*/ 
function isExpired(DateTime $startDate, DateInterval $validFor) 
{ 
    $now = new DateTime(); 

    $expiryDate = clone $startDate; 
    $expiryDate->add($validFor); 

    return $now > $expiryDate; 
} 

$startDate = new DateTime('2013-06-16 12:36:34'); 
$validFor = new DateInterval('P2D'); // valid for 2 days (48h) 
$isExpired = isExpired($startDate, $validFor); 

这种方式,您还可以测试不是整个天其他时期,它适用于Windows服务器可以使用旧的PHP版本(有一个错误,DateInterval->days总是返回6015)。

0

对于不想与天上班的人谁...

你可以得到一个Unix时间戳与DateTime::getTimestamp()方法。 unix时间戳以秒为单位,这很容易处理。所以,你可以这样做:

$now = new DateTime(); 
$nowInSeconds = $now->getTimestamp(); 

$confirmationRequestedAtInSeconds = $confirmationRequestedAt->getTimestamp(); 

$expired = $now > $confirmationRequestedAtInSeconds + 48 * 60 * 60; 

$expiredtrue如果时间过期