Home > OS >  Checking the opening hours by condition
Checking the opening hours by condition

Time:12-11

Hello i have little problem with my script.

ad_otwarcie (row in database) - opening time of the restaurant

ad_zamkniecie (row in database) - restaurant closing time

$current_time = date('H:i'); // checks current time
$closed_soon = date("H:i", strtotime("-5 minutes", strtotime($row['ad_zamkniecie']))); // closing time - 5 mins

if($current_time >= date($row['ad_otwarcie']) && $current_time <= date($row['ad_zamkniecie'])) {
  echo "The place (ex. restaurant) is open";
} elseif($current_time >= $closed_soon && $current_time <= date($row['ad_zamkniecie']) ) {
  echo "The place (ex. restaurant) will close in 5 mins";
} elseif($current_time >= date($row['ad_zamkniecie'])) {
  echo "The place (ex. restaurant) is closed";
}

If there is no middle condition (I mean the one regarding closing the restaurant in 5 minutes) all is well. Conversely, if that adds up, it becomes a problem. It doesn't tell me "restaurant will close in 5 minutes" but only "restaurant open".

I would like to make it worked.

CodePudding user response:

The problem is you are passing the times to the date function in your if statements. You only need to compare the strings themselves. You can also put the logic in a function to simplify:

<?php

$open_time = '09:00';
$close_time = '17:00';

function place_open_status($open_time, $close_time, $current_time = null)
{
    if (is_null($current_time))
        $current_time = date('H:i');
    
    $closed_soon = date('H:i', strtotime('-5 minutes', strtotime($close_time)));

    if ($current_time >= $open_time && $current_time < $closed_soon)
        return ['open', 'The place (ex. restaurant) is open'];
    
    if ($current_time >= $closed_soon && $current_time < $close_time)
        return ['closing_soon','The place (ex. restaurant) will close in 5 mins'];

    return ['closed','The place (ex. restaurant) is closed'];
}

var_dump('Should be open: ' . place_open_status($open_time, $close_time, '10:00')[0]);
var_dump('Should be closing_soon: ' . place_open_status($open_time, $close_time, '16:58')[0]);
var_dump('Should be closed: ' . place_open_status($open_time, $close_time, '17:24')[0]);

while (...) {
    $status = place_open_status($row['ad_otwarcie'], $row['ad_zamkniecie']);
    echo '<div >'.$status[1].'</div>';
}

This will return:

string(20) "Should be open: open"
string(36) "Should be closing_soon: closing_soon"
string(24) "Should be closed: closed"
  • Related