How to compare times in PHP?
I want to say this:
$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"; }
The above code does not print ok. I expected it to.
Interval Between Different Dates In order to compare those two dates we use the method diff() of the first DateTime object with the second DateTime object as argument.
When you have two datetime objects, the date and time one of them represent could be earlier or latest than that of other, or equal. To compare datetime objects, you can use comparison operators like greater than, less than or equal to. Like any other comparison operation, a boolean value is returned.
$ThatTime ="14:08:10"; if (time() >= strtotime($ThatTime)) { echo "ok"; }
A solution using DateTime
(that also regards the timezone).
$dateTime = new DateTime($ThatTime); if ($dateTime->diff(new DateTime)->format('%R') == '+') { echo "OK"; }
http://php.net/datetime.diff
To see of the curent time is greater or equal to 14:08:10 do this:
if (time() >= strtotime("14:08:10")) { echo "ok"; }
Depending on your input sources, make sure to account for timezone.
See PHP time() and PHP strtotime()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With