PHP:检查DateTime是否过期

4

我有一个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;
}

谢谢 :) 看看我如何处理变量名 - bodokaiser
它的格式与 date() 稍有不同,请查看 DateInterval::format()。但是请注意,在 DateInterval 中没有名为 hours 的成员变量。请查阅文档 :) - dan-lee
嗨,我注意到这个“bug-canidate”,但首先它还可以 :) - bodokaiser
4个回答

6
$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,返回实际的天数差异。

最好使用(float)$diff->format('%R%a');而不是$diff->days。 - Jeffrey Nicholson Carré

3

0

对于不想使用日期的人...

您可以使用DateTime::getTimestamp()方法获取Unix时间戳。 Unix时间戳以秒为单位,易于处理。因此,您可以执行以下操作:

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

$confirmationRequestedAtInSeconds = $confirmationRequestedAt->getTimestamp();

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

$expired 如果时间过期,则为 true


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);

这样你也可以测试除了整天之外的其他时间段,而且它也适用于使用旧版本PHP的Windows服务器(因为DateInterval->days返回始终为6015存在一个错误)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接