How to compare two time in PHP

I had two times in the format like 7:30:00 and 22:30:00 stored in the variables $resttimefrom and $resttimeto respectively.

I want to check whether the current time is between these two values. I am checking this with the code

$time = date("G:i:s");
if ($time > $resttimefrom and $time < $resttimeto ){
    $stat = "open";
} else {
    $stat = "close";
} 

But I am always getting the $stat as Close. What may cause that?


you can try using strtotime

$st_time    =   strtotime($resttimefrom);
$end_time   =   strtotime($resttimeto);
$cur_time   =   strtotime(now);

then check

if($st_time < $cur_time && $end_time > $cur_time)
{
   echo "WE ARE CLOSE NOW !!";
}
else{
   echo "WE ARE OPEN  NOW !!";
}

i hope this may help you..


A simple yet smart way to do this is to remove the ':' from your dates.

$resttimefrom = 73000;
$resttimeto = 223000;

$currentTime = (int) date('Gis');

if ($currentTime > $resttimefrom && $currentTime < $resttimeto )
{
    $stat="open";
}
else
{
    $stat="close";
} 

$today = date("m-d-y ");
$now = date("m-d-y G:i:s");

if (strtotime($today . $resttimefrom) < $now && $now > strtotime($today . $resttimeto)) {
    $stat = 'open';
else
    $stat = 'close

Try reformatting them into something that you can compare like that. For example, numbers:

$resttimefrom = mktime(7,30,0);
$resttimeto = mktime(22,30,0);

$time = mktime(date('H'),date('i'),date('s'));

You are comparing strings.
Convert the Time Strings to timestamps with strtotime().
Then compare against time().