Home > Article > Backend Development > How to Compare Times in PHP and Fix a Common Error?
In PHP, comparing times can be achieved using different approaches. Let's explore them and resolve a specific issue in comparing times.
Problem:
The given code fails to compare time correctly and output "ok" as expected:
$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"; }
Solution 1:
Use the strtotime() function to convert the time string to a timestamp:
$ThatTime ="14:08:10"; if (time() >= strtotime($ThatTime)) { echo "ok"; }
Solution 2:
Utilize the DateTime class, which also considers time zones:
$dateTime = new DateTime($ThatTime); if ($dateTime->diff(new DateTime)->format('%R') == '+') { echo "OK"; }
Reference:
https://php.net/datetime.diff
The above is the detailed content of How to Compare Times in PHP and Fix a Common Error?. For more information, please follow other related articles on the PHP Chinese website!