Reputation: 47
So I'm trying to create an open and close message with PHP for a webshop where visitors can order.
The storehours are currently stored in this format:
1 12:00-22:00
2 12:00-23:00
3 closed-closed
4 12:00-02:50
5 12:00-23:00
etc..
So for the first 3 days. it's pretty easy to print a closed message as you just compare the strings with date("Hi") and check if the current time is between de store hours. But when it comes to the 4th day, with overnight hours I get to struggle. As the time hits 00:00 it checks, of course, the closing date of day 5, while actually, it should check if it is open at night.
Is there a reliable way of getting this to work?
Upvotes: 2
Views: 476
Reputation: 60413
I didn't account for your closed-closed
scenario but thats a simple check.
$open_close = explode('-', $hours);
// current date and time
$now = new DateTime();
// clone the current datetime and explicity set the time to the open time
$open = clone $now;
$open_time = explode(':', $open_close[0]);
call_user_func_array([$open, 'setTime'], $open_time);
// do the same for the close time
$close_time = explode(':', $open_close[1]);
$close = clone $now;
call_user_func_array([$close, 'setTime'], $close_time);
// if close is greater than close, the close must be the next day unless its a data entry error, but we cant really prevent that, so assume its good and modify the date time for close to be the next day
if ($open > $close) {
$close->modify('+1 day');
}
// now a basic comparison to see if $now is between $open and $close
if ($now < $close && $now >= $open) {
echo 'OPEN';
} else {
echo 'Closed';
}
I also didn't address your need to map the days of week to the current day, i assume you have already managed that. If not then you will need to do some tweaking i think, but this should overall get you an accurate comparison.
Upvotes: 2
Reputation: 23958
I think this can work.
I convert the open and close times to a unix value.
If close is before open I add one day in seconds.
Now I have a unix value of when it opens and when it closes today and all I need to do is to compare against time().
$otime="16:15";
$ctime="00:50";
$open = strtotime(date("Y-m-d ").$otime);
$close = strtotime(date("Y-m-d ").$ctime);
If($close<$open) $close += 3600*24;
If(time() >= $open && time() < $close){
Echo "open";
}Else{
Echo "closed";
}
Upvotes: 1