Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Check if DateTime isn't expired

I have a DateTime Object which holds an past timestamp.

I would now like to check if this DateTime is older than for example 48Hours.

How can I compore them best?

Regards

EDIT: Hi,

thanks for the help. Heres the helper method. Any naming suggesstions?

    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;
}
like image 369
bodokaiser Avatar asked Nov 16 '25 01:11

bodokaiser


1 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::diff returns a DateInterval object, which has a member variable days that returns the actual day difference.

like image 127
dan-lee Avatar answered Nov 17 '25 17:11

dan-lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!