>我有一个保存过去时间戳的日期时间对象。
我现在想检查此日期时间是否早于例如 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;
}
$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 对象,该对象具有返回实际日差的成员变量days
。
你可能想看看这里:如何比较 PHP 5.2.8 中的两个日期时间对象?
因此,最简单的解决方案可能是创建另一个日期为 NOW -48Hour 的 DateTime
对象,然后与之进行比较。
我知道
这个答案有点晚了,但也许它可以帮助其他人:
/**
* 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);
通过这种方式,您还可以测试整天以外的其他时间段,并且它也适用于具有较旧PHP版本的Windows服务器(日期间隔->天始终返回6015的错误)。
对于那些不想与日子一起工作的人...
您可以使用 DateTime::getTimestamp() 方法获取 unix 时间戳。Unix 时间戳以秒为单位,这很容易处理。所以你可以做到:
$now = new DateTime();
$nowInSeconds = $now->getTimestamp();
$confirmationRequestedAtInSeconds = $confirmationRequestedAt->getTimestamp();
$expired = $now > $confirmationRequestedAtInSeconds + 48 * 60 * 60;
如果时间过期,$expired
将被true