【问题标题】:PHP: Check if DateTime isn't expiredPHP:检查日期时间是否未过期
【发布时间】:2012-04-17 19:10:40
【问题描述】:

我有一个包含过去时间戳的 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;
}

【问题讨论】:

  • 谢谢 :) 让我们看看我如何处理 var 名称
  • 它的格式与date() 略有不同,请查看DateInterval::format()。但要注意DateInterval 中没有hours 这样的成员变量。请查看文档:)
  • 嗨,我注意到了这个“bug-canidate”,但首先它没问题 :)

标签: php datetime compare


【解决方案1】:
$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 返回实际的日差。

【讨论】:

  • 更好用 (float)$diff->format('%R%a');而不是 $diff->days
【解决方案2】:

您可能想看这里: How do I compare two DateTime objects in PHP 5.2.8?

因此,最简单的解决方案可能是创建另一个日期为 NOW -48Hours 的 DateTime 对象,然后进行比较。

【讨论】:

    【解决方案3】:

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

    /**
     * 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 存在错误)。

    【讨论】:

      【解决方案4】:

      对于不想每天工作的人...

      您可以使用 DateTime::getTimestamp() 方法获取 unix 时间戳。 unix 时间戳以秒为单位,易于处理。所以你可以这样做:

      $now = new DateTime();
      $nowInSeconds = $now->getTimestamp();
      
      $confirmationRequestedAtInSeconds = $confirmationRequestedAt->getTimestamp();
      
      $expired = $now > $confirmationRequestedAtInSeconds + 48 * 60 * 60;
      

      如果时间到期,$expired 将变为 true

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-27
        • 2011-02-19
        • 1970-01-01
        • 2012-05-27
        • 2022-01-20
        • 2011-12-26
        相关资源
        最近更新 更多