I'm trying to calculate if the current time is within the opening hours of a restaurant.
This question has been asked a lot on Stackoverflow, but I haven't found one that can account for the problems I am having. Also, would be nice to see idea on a better way to do this.
Currently it breaks if the day is closed (Sunday in this example) or if it's 1am on "Saturday" (so technically 1am Sunday morning). I have a feeling I'll have to change the way the data is stored to account for after midnight, but I'm trying to work with what I have for now. It's a problem, because most restaurants list their opening times for a given day as 5pm - 2am, not 5pm - 12am, 12am - 2am.
Anyway, here is what I have. Please tell me a better way to do it.
I have times stored like this:
$times = array(
'opening_hours_mon' => '9am - 8pm',
'opening_hours_tue' => '9am - 2am',
'opening_hours_wed' => '8:30am - 2am',
'opening_hours_thu' => '5:30pm - 2am',
'opening_hours_fri' => '8:30am - 11am',
'opening_hours_sat' => '9am - 3pm, 5pm - 2am',
'opening_hours_sun' => 'closed'
);
This is the code I'm using now:
// Get the right key for today
$status = 'open';
$now = (int) current_time( 'timestamp' );
$day = strtolower( date('D', $now) );
$string = 'opening_hours_'.$day;
$times = $meta[$string][0]; // This should be a stirng like '6:00am - 2:00am' or even '6:00am - 11:00am, 1:00pm to 11:00pm'.
// Does it contain a '-', if not assume it's closed.
$pos = strpos($times, '-');
if ($pos === false) {
$status = 'closed';
} else {
// Maybe a day has multiple opening times?
$seating_times = explode(',', $times);
foreach( $seating_times as $time ) {
$chunks = explode('-', $time);
$open_time = strtotime($chunks[0]);
$close_time = strtotime($chunks[1]);
// Calculate if now is between range of open and closed
if(($open_time <= $now) && ($now <= $close_time)) {
$status = 'open';
break;
} else {
$status = 'closed';
}
}
}