Determining if two time ranges overlap at any point

algorithm, php

Solution

The logic is correct. The timestamps you provided for `$red` (8-8:50pm) and `$orange` (1:30-3:30pm) do not overlap.

Given correct values (that reflect your screenshot), the overlap is indeed found:

function show_date($value, $key) {
    echo $key, ': ', date('r', $value), PHP_EOL;
}

$red = array('start' => strtotime('today, 2pm'), 'end' => strtotime('today, 2:45pm'));
$orange = array('start' => strtotime('today, 1:30pm'), 'end' => strtotime('today, 4pm'));

array_walk($red, 'show_date');
array_walk($orange, 'show_date');

if (($red['start'] <= $orange['end']) && ($red['end'] >= $orange['start'])) {
    echo 'Conflict handling';
}

My guess would be you have a timezone conversion issue.

Problem

Possible Duplicate: Determine Whether Two Date Ranges Overlap I am trying to work out if two time ranges in PHP overlap. I've been referring to Determine Whether Two Date Ranges Overlap for my initial try, however, it's not matching all cases. If a time range is nested in between the start and end times of another time range, it's not being matched. If it overlaps the beginning or the end of the shift, or if the shifts are exact matches, it works as expected. Check out this image of what I'm talking about: Basically, I am trying to hide any orange shifts if they overlap any red shifts anywhere. Here's the relevant portion of code I'm trying to use to make this happen. ``` if(($red['start'] <= $orange['end']) && ($red['end'] >= $orange['start'])) { //Conflict handling } ``` The values of the variables are UNIX timestamps. Working through the numbers logically, I understand why the statement above fails. There are obviously ways I could do more logic to determine if the one shift falls in the other shift (which is what I may need to do), but I was hoping for a more universal catch. EDIT: Adding the values of each block's start and end time. I agree what I have should work. The fact that it isn't is where my issue lies. I'm probably overlooking something dumb. ``` orange-start = 1352899800 orange-end = 1352907000 red-start = 1352923200 red-end = 1352926200 ``` Therefore my logic would state: ``` if((1352923200 <= 1352907000) && (1352926200 >= 1352899800)) ``` So following that, the first comparison fails. EDIT 2: It looks like my logic is sound (which I thought was the case), and my issue is something related to the UNIX timestamp not matching the actual time being displayed. I thank those who worked though this with me and help me discover that as being the issue. I wish I could accept both Andrey's and Jason's answers.

Original source

Related problems