Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check a PHP Time(H:i:s) reside between two times(H:i:s)

Tags:

php

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 contain the $at_time or not.

like image 525
The System Restart Avatar asked Dec 21 '22 01:12

The System Restart


2 Answers

My PHP is a bit 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 the ranges which contain the $at_time.

like image 109
Jimmery Avatar answered Jan 07 '23 05:01

Jimmery


Note: inspired by the answer of @Jimmery above.

You can put it into a function which returns the matched range or false - additionally it has the small 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;
}
like image 37
Jost Avatar answered Jan 07 '23 07:01

Jost