Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two time in PHP

Tags:

php

datetime

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?

like image 268
Rajasekar Avatar asked Aug 04 '10 08:08

Rajasekar


People also ask

Can you compare time in PHP?

In order to compare those two dates we use the method diff() of the first DateTime object with the second DateTime object as argument. The diff() method will return a new object of type DateInterval .

How to compare 2 string dates in PHP?

Comparing two dates in PHP is simple when both the dates are in the same format but the problem arises when both dates are in a different format. Method 1: If the given dates are in the same format then use a simple comparison operator to compare the dates. echo "$date1 is older than $date2" ; ?>

How can I compare two DateTime strings?

If both the date/time strings are in ISO 8601 format (YYYY-MM-DD hh:mm:ss) you can compare them with a simple string compare, like this: a = '2019-02-12 15:01:45.145' b = '2019-02-12 15:02:02.022' if a < b: print('Time a comes before b. ') else: print('Time a does not come before b.


1 Answers

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..

like image 122
Zuber Surya Avatar answered Sep 28 '22 16:09

Zuber Surya