0

I'm trying to write a quick function that would compare the current time to business hours and display open closed status:

  • If open, display when closing
  • If closed, display time when opening
  • The $schedule object could be populated dynamically
  • Each day object will have one start and stop time
  • Some days will not be open

My function was mostly borrowed from: Determine If Business Is Open/Closed Based On Business Hours

Where I'm stuck: When close grab the next item in the array to determine the opening time. (3 & 4th if statement) i.e. determine when 'tomorrow' actually is to display "open [tomorrow] at [starttime]

    <?php
$schedule = [
    'Mon' => ['10:00 AM' => '12:00 PM'],
    'Tue' => ['08:00 AM' => '06:00 PM'],
    'Wed' => ['08:00 AM' => '06:00 PM'],
    'Thu' => ['08:00 AM' => '06:00 PM'],
    'Fri' => ['08:00 AM' => '06:00 PM'],
    'Sat' => ['08:00 AM' => '02:00 PM'],
    'Sun' => ['01:00 AM' => '01:00 AM']
];


$tz = 'America/Detroit';
date_default_timezone_set($tz);
$timestamp = time();
//$currentTime = (new DateTime("now", new DateTimeZone($tz)))->setTimeStamp($timestamp); 
$currentTime = (new DateTime("now"))->setTimeStamp($timestamp);
$status = 'Closed - It Must Be Sunday';

foreach ($schedule[date('D', $timestamp)] as $startTime => $endTime) {
    $startTime = DateTime::createFromFormat('h:i A', $startTime);
    $endTime   = DateTime::createFromFormat('h:i A', $endTime);
    
    // open check
    if (($startTime < $currentTime) && ($endTime > $currentTime )) {
        $status = ' Open - Closing at ' . $endTime->format('g:i A');
        break;
    }
    // closed check - to early
    if (($startTime > $currentTime) && ($endTime > $currentTime )) { 
        $status = ' Closed - Opening Today at ' . $startTime->format('g:i A');
        break;
    }
     // closed check - to late
      if (($startTime < $currentTime) && ($endTime < $currentTime )) { 
        // Grab the next day
        foreach ($schedule[date('D', $timestamp = strtotime('+1 days', $timestamp);)] as $startTime => $endTime) {
            $nextOpen = DateTime::createFromFormat('h:i A', $startTime); 
        }
        $status = ' Closed - Open [tomorrow] at ' . $nextOpen->format('g:i A');
        break;
    }
     if (($startTime = $endTime)) {
        $status = ' Closed - All Day - Open Tomorrow at';
        break;
    }

}
print $status;
?>
DDulla
  • 659
  • 9
  • 20
  • and what is the problem? – Flash Thunder Dec 13 '21 at 18:06
  • You need to check is it closed first and break the loop. In your example for Sunday if somebody checked at 12:30AM he/she will see "too early", because this will pass your second if statement. E.g current time is 01:30AM he / she will see "too late". Meanwhile I would suggest you to refactor and restructure a bit your code. Break it to functions like getNextOpenDay, getCurrentSchedule avoid those foreach loops etc.. Regards Davit. – Davit Dec 13 '21 at 19:10

0 Answers0