-1

I am trying to write a script which will display either an open or closed message depending on a businesses operating hours. I tried using the solution found here and adding to this by setting the timezone. However when I try to run this the value of $status is always 'closed' even if the time of day falls within the values in the array.

Here is my code, any advice would be appreciated. Thanks

//setting default timezone
date_default_timezone_set('Europe/Dublin');
//creating array of opening hours
$openingHours = [
'Sun' => ['12:00' => '20:30'],
'Wed' => ['16:00' => '21:00'],
'Thu' => ['16:00' => '21:00'],
'Fri' => ['16:00' => '23:00'],
'Sat' => ['16:00' => '21:00']
];



//current timestamp
$timestamp = time();

//default status
$status = 'closed';

//get time object from timestamp
$currentTime = (new DateTime())->setTimestamp($timestamp);

//loop through time range for current day
foreach ($openingHours[date('D', $timestamp)] as $startTime => $endTime) {

//create time objects from start and end times
$startTime = DateTime::createFromFormat('h:i A', $startTime);
$endTime = DateTime::createFromFormat('h:i A', $endTime);

//check if current time is within range
if (($startTime < $currentTime) && ($currentTime < $endTime)) {
$status = 'open';
break;
}//end off if

}//end off foreach

echo "we are currently :$status";
Sabathaon
  • 45
  • 8

1 Answers1

0

In your code the currentTime variable is an object so when you try comparing it things aren't going to match. Try this instead which simplifies things a little.

date_default_timezone_set('Europe/Dublin');
//creating array of opening hours
$openingHours = [
'Sun' => ['12:00' => '20:30'],
'Wed' => ['16:00' => '21:00'],
'Thu' => ['16:00' => '21:00'],
'Fri' => ['16:00' => '23:00'],
'Sat' => ['16:00' => '21:00']
];

//default status
$status = 'closed';

$timeNow = date('H:m',time());

//loop through time range for current day
foreach ($openingHours[date('D', time())] as $startTime => $endTime) {
    //check if current time is within range
    if (($startTime < $timeNow) && ($timeNow < $endTime)) {
        $status = 'open';
        break;
    }  //end off if
}  //end off foreach

echo "we are currently :$status";

Edit on July 7th:

If you can change you the opening hours array slightly you may avoid multiple calls to date and the foreach loop using the code below.

date_default_timezone_set('Europe/Dublin');
//creating array of opening hours
$openingHours = [
'Sun' => ['Open'=>'12:00','Close' => '20:30'],
'Wed' => ['Open'=>'16:00','Close' => '21:00'],
'Thu' => ['Open'=>'16:00','Close' => '21:00'],
'Fri' => ['Open'=>'16:00','Close' => '23:00'],
'Sat' => ['Open'=>'16:00','Close' => '21:00']
];

$timeNow = date('H:m',time());
$dow     = date('D',time());

echo 'We are currently :' . ((($openingHours[$dow]['Open'] < $timeNow) AND
                              ($timeNow < $openingHours[$dow]['Close'])) ? 'open' : 'closed');
Dave
  • 5,108
  • 16
  • 30
  • 40