manohar khadka manohar khadka - 6 months ago 12
PHP Question

Determine if time interval doesn't intersect with another time interval?

Hellow world , i wanna find out if two shifts (time interval) are unique or doesn't intersect with each other..
what i did so far is :

**Time interval 1**
$starttime1 = '23:00:00';
$endtime1 = '04:00:00';


**Time interval 2**
$starttime2 = '19:00:00';
$endtime2 = '23:30:00';

if(($starttime1 < $starttime2 && $endtime1 <= $starttime2) || ($starttime1 >= $endtime2 && $endtime1 > $endtime2)){
echo ("intersect");
} else {
echo ("doesn't intersect");
}


The problem is, two time interval shown above should have been intersect but doesn't..starttime1 lies between second interval of time..
In case if two time interval are in same order ( ascending or descending) something like...

**Time interval 1**
$starttime1 = '23:00:00';
$endtime1 = '04:00:00';


**Time interval 2**
$starttime2 = '23:30:00';
$endtime2 = '19:30:00';


that's working fine..Otherwise not..Thanks in advance.

Answer

The string comparison does not work. Use numbers instead:

First convert the times to a number:

function convert($t)
{
    list ($h, $m, $s) = explode(':', $t);
    return $s + 60 * ($m + 60 * $h);
}

And in the event of an end time smaller than the start time, add one day i.e.

$one_day = 24 * 60 * 60;
$starttime1 = convert('23:00:00');
$endtime1 = convert('04:00:00');

if ($endtime1 < $starttime1) {
    $endtime1 += $one_day;
}

$starttime2 = convert('19:00:00');
$endtime2 = convert('23:30:00');

if ($endtime2 < $starttime2) {
    $endtime2 += $one_day;
}

Now for it to intersect either the start/end times of occur in the range of the other

i.e.

if (($endtime2 >= $starttime1 && $endtime2 <= $endtime1) ||
    ($starttime2 >= $starttime1 && $starttime2 <= $endtime1))
{
    echo ("intersect");
} else {
    echo ("doesn't intersect");
}

Here is it working!

Comments