PHP: How to compare a time string with date('H:i')?
You can use this:
$myTime = '19:30';
if (date('H:i') == date('H:i', strtotime($myTime))) {
// do something
}
You can construct a new DateTime object, setting the time on a random date. Than compare those two objects. eg:
$my_time = new DateTime('January 1th 1970 19:30');
$comparable_time = new DateTime('January 1th 1970 '. date('H:i'));
if($my_time < $comparable_time) {
// do something
} else {
// do something else
}
Please take note of the changelog;
Version 5.2.2 DateTime object comparison with the comparison operators changed to work as expected. Previously, all DateTime objects were considered equal (using ==).
You can't use the comparison operators with strings like that, because when you do the strings get converted to numbers first.
For an one-liner solution, you can use strcmp
:
if(strcmp($my_time, date('H:i')) == 1)
{
do something ...
}
The condition above is semantically equivalent to "if $my_time is greater than the current time", but only if the format of the strings remains consistent! It's very easy to introduce a bug in this code if for any reason the format of $my_time
does not directly correspond to the H:i
pattern.
Dumbing down the values to strings is usually not the way you should be going about using dates and times. A more appropriate solution would be to use the native DateTime
class, introduced in PHP 5.2.0 (John Conde has already given an example in his answer).
However, there is also one possible advantage to treating times as dumb scalar values: the results are consistent with the human perception that 01:00 is always later than 00:00. DateTime
approaches are dependent on the local timezone and date, and might not always give you the expected results. Example:
// assume we are in London
date_default_timezone_set('Europe/London');
// assume that today is March 25, 2012
$date1 = new DateTime("2012-03-25 01:00:00");
$date2 = new DateTime("2012-03-25 02:00:00");
// and...
if ($date1 == $date2) {
echo "WTF?!? Equal???";
}
See it in action.
The result of this test is different than what comparing some scalar representation of "01:00" and "02:00", so it's a good idea to think about what the proper semantics are for the comparison.