-1

I am trying to get the result that which time is greater. I mean there is no date only time.

$open_time  = date("g:i A", strtotime($restaurant['open_time']));
$close_time = date("g:i A", strtotime($restaurant['close_time']));
$curren_time = date("h:i");

$restaurant['open_time'] and $restaurant['close_time'] is the result from database. It is coming in 24 hour format like 22:30, 10:20.

What i want exactly.

if(($current_time > $open_time) &&  ($current_time < $close_time)
{
   echo "Opened";
}
else
{
   echo "Closed";
}

If current_time is 2:00 AM and open_time is 11:00 AM then the result should echo Closed. And like this if current_time is 1:00 PM and closed_time is 11:00 PM then the result should echo Opened. Hope i explained well. Please ask if you have any doubt in my question.

You can solve thus using 24 hour format time also. But remember you can add date but virtually not from database. You can use to get the greater time

Binayak Das
  • 618
  • 8
  • 20
  • whats happening now? if there is no date then it just numbers comparison . is it ? – zod Jun 30 '17 at 22:01
  • Possible duplicate of [How to check if time is between two times in PHP](https://stackoverflow.com/questions/15911312/how-to-check-if-time-is-between-two-times-in-php) – BenRoob Jun 30 '17 at 22:03
  • Using date that I have done. But there is no date in my database. Hope you understood @zod – Binayak Das Jun 30 '17 at 22:05
  • you have only time in database can you tell whats the value for open & close – Omi Jun 30 '17 at 22:06
  • Already given in question. Open time 11: 00 and close time 22:00. Like this. @omi – Binayak Das Jun 30 '17 at 22:08

1 Answers1

2

Set correct timezone and should work.

$restaurant = [
    'open_time' => '11:00',
    'close_time' => '22:00'
];

$timeZone = new DateTimeZone('Europe/Warsaw');
$now = new DateTime('now', $timeZone);
$open = DateTime::createFromFormat('H:i', $restaurant['open_time'], $timeZone);
$close = DateTime::createFromFormat('H:i', $restaurant['close_time'], $timeZone);

$working_now = ($now > $open && $now < $close);

if ($working_now) {
    echo 'open';
} else {
    echo 'closed';
}

You can play with it in sandbox - uncomment the test line to change current time.

If it's open through midnight you might need additional logic there:

if ($open > $close) {
    if ($now > $close) {
        $close->modify('+1 day');
    } else {
        $open->modify('-1 day');
    }
}

$working_now = ...
shudder
  • 2,076
  • 2
  • 20
  • 21