PHP: check if DateTime is expiring

I have a DateTime object that contains the past timestamp.

Now I want to check if this DateTime is older than, for example, 48 hours.

How can I compost them better?

Hi

EDIT: Hi,

thanks for the help. Heres a helper method. Any suggestions for naming?

    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;
}
+3
source share
4 answers
$a = new DateTime();
$b = new DateTime('-3days');

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

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

I used $ a and $ b for testing purposes. DateTime::diffreturns a DateInterval object that has a member variable daysthat returns the actual difference per day.

+4
source

You can look here: How to compare two DateTime objects in PHP 5.2.8?

, , DateTime, NOW -48Hours, .

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

Thus, you can also test periods other than whole days, and it works on Windows servers with older versions of PHP (there was an error with DateInterval-> days returning always 6015).

0
source

For people who do not want to work with the days ...

You can get the unix timestamp using the DateTime :: getTimestamp () method . The unix timestamp is in seconds, which is easy to handle. So you can do:

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

$confirmationRequestedAtInSeconds = $confirmationRequestedAt->getTimestamp();

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

$expiredwill be trueif time is up

0
source

All Articles