Check the PHP time (H: i: s) between two points (H: i: s)

Suppose

$at_time = '07:45:00'; $ranges = [ ['start' => '09:00:00', 'end' => '17:00:00'], ['start' => '17:00:00', 'end' => '08:59:00'] ]; 

Now I want to check that $ranges contains $at_time or not.

+4
source share
4 answers

My PHP is a little rusty, but try something like:

 $matches=Array(); foreach($ranges as $i=>$ikey){ if(strtotime($ranges[$i]['start']) < strtotime($at_time) && strtotime($ranges[$i]['end']) > strtotime($at_time)){ array_push($matches,$i); } } 

Then $matches will contain an array of all ranges containing $at_time .

+4
source

That should work.

 <?php function arrayContainsTime($time, $ranges) { $target = strtotime($time); foreach($ranges as $range) { $start = strtotime($range['start']); $end = strtotime($range['end']); if($target > $start && $target < $end) { return 1; } } return 0; } $at_time = '07:45:00'; $another_time = '10:30:45'; $ranges = [ ['start' => '09:00:00', 'end' => '17:00:00'], ['start' => '17:00:00', 'end' => '08:59:00'] ]; echo $at_time, " match? ", arrayContainsTime($at_time, $ranges); echo "<br>"; echo $another_time, " match? ", arrayContainsTime($another_time, $ranges); 

See here in action!

Note: it will not detect 17:00:00 → 08:59:00 correctly, because the date is not specified.

+3
source

Note: inspired by @Jimmery's answer above.

You can put it in a function that returns a consistent range or false - in addition, it has a slight advantage that it stops with the first match:

 function timeInRange($at_time,$ranges) { foreach($ranges as $i=>$ikey) { if(strtotime($ranges[$i]['start']) < strtotime($at_time) && strtotime($ranges[$i]['end']) > strtotime($at_time)) { return $i; } } return false; } 
+2
source

That should give you a way

 $time = str_replace(":","",$at_time); foreach($ranges as $rangleval){ $start = str_replace(":","",$rangleval['start']); $end = str_replace(":","",$rangleval['end']); if($start<=$time && $end>=$time){ echo $at_time." lies between ".$rangleval['start']." and ".$rangleval['end']; break; } } 
+1
source

Source: https://habr.com/ru/post/1498330/


All Articles