PHP 比较时间

2022-08-30 09:51:56

如何比较PHP中的时间?

我想说的是:

$ThatTime ="14:08:10";
$todaydate = date('Y-m-d');
$time_now=mktime(date('G'),date('i'),date('s'));
$NowisTime=date('G:i:s',$time_now);
if($NowisTime >= $ThatTime) {
    echo "ok";
}

上面的代码打印不正常。我早就预料到了。


答案 1
$ThatTime ="14:08:10";
if (time() >= strtotime($ThatTime)) {
  echo "ok";
}

使用(也考虑时区)的解决方案。DateTime

$dateTime = new DateTime($ThatTime);
if ($dateTime->diff(new DateTime)->format('%R') == '+') {
  echo "OK";
}

http://php.net/datetime.diff


答案 2

要查看当前时间是否大于或等于 14:08:10,请执行以下操作:

if (time() >= strtotime("14:08:10")) {
  echo "ok";
}

根据您的输入源,请务必考虑时区。

参见 PHP time()PHP strtotime()


推荐