user2534610
user2534610

Reputation: 3

Failing to check if time is in the past using strtotime

I am trying to check if a certain time is in the past. Solution 1 works but the solutions 2 and 3 using strtotime do not. Any ideas why the strtotime solutions fail with this date when they work fine when the date is not that distant (f.ex. using 27.05.2035 works)?

  <?php
$date = "27.05.2045";
$hour = "22";
$min = "15";

// 1. This one works
$datetime = DateTime::createFromFormat('d.m.Y H:i', $date.' '.$hour.':'.$min);
$now = new DateTime();
  if ($datetime < $now)
{
echo "Datetime is in the past";
}

else if ($datetime > $now)
{
echo "Datetime is in the future";
}

// 2. Does not work
  if (time() > strtotime($date.' '.$hour.':'.$min))
{
echo "Datetime is in the past (strtotime)";
}
else if (time() < strtotime($date.' '.$hour.':'.$min))
{
echo "Datetime is in the future (strtotime)";
}    

// 3. Using another date format but still does not work
$array  = explode('.', $date);
$date_converted = $array[2].'-'.$array[1].'-'.$array[0];

  if (time() > strtotime($date_converted.' '.$hour.':'.$min))
{
echo "Datetime is in the past (strtotime with converted date)";
}
else if (time() < strtotime($date_converted.' '.$hour.':'.$min))
{
echo "Datetime is in the future (strtotime with converted date)";
}    

?>

Upvotes: 0

Views: 163

Answers (1)

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174997

The 32 bit integer maximum makes it impossible to represent dates past 19 January 2038.

The solution would be to either:

  1. Use DateTime objects, which do not represent dates using the number of seconds passed since 1970, but using a field for each time unit.
  2. Use the 64-bit version of PHP, where the maximum integer is much higher.

See The 2038 Year Problem for more details.

Upvotes: 1

Related Questions