Good time! I try to check the time in the format HH: MM is a function that, through str_replace, cuts Ymd H from the current time format: i: s (2017-12-02 17:08:11) and writes it to the $ new variable. Further it is required to make comparisons like:

if ($new >= "13:00" && $new <= "15:45") { //операции } 

but the comparison is not correct as I understood because time is compared in the format of strings. Is there any way to compare it so that there are no glitches? but it is very necessary that it would be compared exactly the clock without specifying a more accurate date, some kind of temporary conversion of the clock to a more complete date can then be compared. But the main thing is that in the if else constructions the time in the hour-minute format is specified.

1 answer 1

Here is another version of the function

 <?php function isBetween($hi, $st, $end) { $hi = strtotime($hi); $st = strtotime($st); $end = strtotime($end); if ($st < $end) { return $st <= $hi && $hi <= $end; } else { return (strtotime('00:00') <= $hi && $hi <= $end) || ($st <= $hi && $hi <= strtotime('23:59')); } } var_dump(isBetween('08:01', '08:00', '17:00')); var_dump(isBetween('07:59', '17:00', '08:00')); var_dump(isBetween('17:00', '17:00', '08:00')); var_dump(isBetween('23:59', '17:00', '08:00')); var_dump(isBetween('07:59', '08:00', '17:00')); var_dump(isBetween('07:60', '08:00', '17:00')); var_dump(isBetween('16:59', '17:00', '08:00')); var_dump(isBetween('24:00', '17:00', '08:00')); var_dump(isBetween('24:00', '08:00', '17:00')); 

Result

 bool(true) bool(true) bool(true) bool(true) bool(false) bool(false) bool(false) bool(false) bool(false) 

Http://sandbox.onlinephpfunctions.com/code/d4580648fe605c1cb4544f5cbb30a9b01455e727 test

At the input, the function waits for strings in the format HH:MM . If you want with seconds, then in the function you need to add to the 23:59 tail :59 .

Returns true if:

  1. $hi is between $st and $end , with $st < $end
  2. $hi <= $st or $hi > = $end , with $st > = $end

PS Use at your own risk.