PHP Time Comparison (H:m)

The database stores data about the company's working hours in the format: 09:00,18:30; 12:00,02:00 It is necessary to compare the current time with two intervals (the beginning/end of the working day) and if the current time is between the working time, return true, otherwise false.

I convert and try to compare it like this:

$start = strtotime($start_work);
$end = strtotime($end_work);

if ($current_time >= $start && $current_time <= $end) {
  ...
} else {
  ...
}

How it works

The company is open from 08: 30 to 18: 00, and the current time is 12: 00. In this case, everything is fine. Everything is correct displays

How it doesn't work

The company is open from 08: 30 to 02: 00, and the current time is 12: 00.

In general, the problem is if any time after midnight. because it is essentially less (from 0) I looked for options, found a lot of questions about this, but I did not find the answer.

How can this issue be resolved? Thanks.

Author: kate, 2017-01-16

2 answers

    <?php
       //Ваши входные данные
      $start_work = "08:00";
      $end_work = "02:00";
      $currentTime = "01:00";

      //текущее время с датой, даже если оно у вас 12:00 все равно имеет дату
      $currentDateTime = strtotime(date('Y-m-d')  ." ". $currentTime); 
      //Дата и время во сколько мы закрылись вчера
      $previousDayEnd;
       //Дата и время во сколько мы открылись сегодня
      $startDateTime;
       //Дата и время во сколько мы закрылись сегодня
      $endDateTime;

 $startDateTime = strtotime(date('Y-m-d')  ." ". $start_work);

 if (strtotime($start_work) <= strtotime($end_work)){
      $endDateTime = strtotime(date('Y-m-d')  ." ". $end_work);
      $previousDayEnd = strtotime(date('Y-m-d')  ." ". $end_work . "-1 days");
 }
 else{
     $endDateTime = strtotime(date('Y-m-d')  ." ". $end_work . "+1 days");
     $previousDayEnd = strtotime(date('Y-m-d')  ." ". $end_work );
 }

 //проверить полученные результаты 
  echo "Мы закрылись в : " .  date("Y-m-d H:i:s", $previousDayEnd). "\n";
 echo "Открытие : " . date("Y-m-d H:i:s", $startDateTime) . "\n"; 
 echo "Закрытие  : " .  date("Y-m-d H:i:s", $endDateTime). "\n"; 

if ($currentDateTime >= $startDateTime && $currentDateTime <= $endDateTime) {
 echo "Сейчас рабочее время : " . date("Y-m-d H:i:s", $currentDateTime) ."\n";
} 
else if($currentDateTime < $startDateTime && $currentDateTime < $previousDayEnd ){
    echo "Сейчас рабочее время : " . date("Y-m-d H:i:s", $currentDateTime) ."\n";
}
else {
  echo "Мы закрыты в это время : " . date("Y-m-d H:i:s", $currentDateTime) ."\n";
}

Play here

 3
Author: koks_rs, 2017-01-16 09:32:20

If the end time is less than the start time, then you need to check two ranges after OR - from the start time to midnight (24:00) and from midnight (00:00) to the end time.

 0
Author: Qwertiy, 2017-01-16 08:16:26