Here's an example that uses DateTime()
which is better for working with dates since it takes daylight savings time and leap years into account. It also makes working with timezones easier.
All this does is create three DateTime objects. One to represent "now". One to represent today at 10am and one to represent today at 10pm. It then checks to see if "now" is after opening time and before closing time. It can do this easily because DateTime objects are comparable (which means you don't have to convert the dates and times into integers or some string format to try to compare them).
$now = new DateTime();
$startTime = new DateTime('10:00');
$endTime = new DateTime('22:00');
if ($now < $startTime) {
// before business hours
}
else if ($now > $endTime) {
// after business hours
}
To check the day of the week you can use the l
modifier to DateTime::format()
. Then you can dynmaically alter the opening and closing times:
$now = new DateTime();
switch ($now->format('l')) {
case 'Monday' :
$open = '10:00';
$close = '22:00';
break;
case 'Tuesday' :
$open = '9:00';
$close = '23:00';
break;
// etc...
}
$startTime = new DateTime($open);
$endTime = new DateTime($close);
if ($now < $startTime) {
// before business hours
}
else if ($now > $endTime) {
// after business hours
}
If your server is not in central timezone, you can modify your code to work with it using DateTimeZone()
.
$timezone = new DateTimeZone('America/Chicago');
$now = new DateTime(null, $timezone);
switch ($now->format('l')) {
case 'Monday' :
$open = '10:00';
$close = '22:00';
break;
case 'Tuesday' :
$open = '9:00';
$close = '23:00';
break;
// etc...
}
$startTime = new DateTime($open, $timezone);
$endTime = new DateTime($close, $timezone);
if ($now < $startTime) {
// before business hours
}
else if ($now > $endTime) {
// after business hours
}