0

How to calculate if something has expired based on date and time in php backend. Also it should work for users regardless of time zone.

Timestamp in database 2020-07-24 21:24:27

Timeout value comes from api 00:03:47

if((2020-07-24 21:24:27 + 00:03:47) < date()) {
echo "expired";
} else {
echo "pending";
}
nloo
  • 13
  • 3
  • Does this answer your question? [How can I compare two dates in PHP?](https://stackoverflow.com/questions/3847736/how-can-i-compare-two-dates-in-php) - just follow the answer there but modify the format to match yours (which includes UTC time) – Jon Jul 24 '20 at 21:13

1 Answers1

0

You dont have timezone info in your dates so i assume dates from db are in the same timezone as server.

Use DateTime, its add() method to add the time from api to it as a DateInterval and then compare it with current time to get the result.

<?php

$timestamp = '2020-07-24 21:24:27';
$timeout = '00:03:47';

function isExpired(string $timestamp, string $timeout): bool {
  $timestampDate = new DateTime($timestamp);
  $timeoutParts = explode(':', $timeout);
  $timestampDate->add(new DateInterval(sprintf('PT%sH%sM%sS', $timeoutParts[0], $timeoutParts[1], $timeoutParts[2])));

  return $timestampDate < new DateTime();
}

// now for me is 2020-07-24 20:37:00
var_dump(isExpired($timestamp, $timeout)); // false
var_dump(isExpired('2020-07-24 20:00:00', '01:00:00')); // false
var_dump(isExpired('2020-07-24 19:00:00', '01:00:00')); // true
var_dump(isExpired('2020-07-23 19:00:00', '12:00:00')); // true
var_dump(isExpired('2020-07-25 19:00:00', '12:00:00')); // false
blahy
  • 1,294
  • 1
  • 8
  • 9