PHP using nested arrays to determine business open closed hours? - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Tuesday, December 14, 2021

PHP using nested arrays to determine business open closed hours?

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;
?>


source https://stackoverflow.com/questions/70339024/php-using-nested-arrays-to-determine-business-open-closed-hours

No comments:

Post a Comment