未能使用 strtotime 检查时间是否在过去


Failing to check if time is in the past using strtotime

我正在尝试检查某个时间是否过去。解决方案 1 有效,但使用 strtotime 的解决方案 2 和 3 不起作用。任何想法为什么 strtotime 解决方案在这个日期失败,当它们在日期不那么遥远时工作正常(例如使用 27.05.2035 有效)?

  <?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)";
}    
?>

32 位整数最大值使得无法表示 2038 年 1 月 19 日之后的日期。

解决方案是:

    使用 DateTime 对象,
  1. 这些对象不使用自 1970 年以来经过的秒数表示日期,而是使用每个时间单位的字段。
  2. 使用 64 位版本的 PHP,其中最大整数要高得多。

有关更多详细信息,请参阅2038年问题