by simon baird

Tuesday, August 25, 2009

Test if two date periods overlap in php

<?php

function overlaps($first_start, $first_end, $second_start, $second_end) {
    return !(
        ($first_start < $second_start && $first_end < $second_start)
        ||
        ($first_start > $second_end && $first_end > $second_end)
    );
}

$tests = array(
    array( 'data=> array(10,20,30,40), 'result=> FALSE ),
    array( 'data=> array(30,40,10,20), 'result=> FALSE ),
    array( 'data=> array(10,40,20,30), 'result=> TRUE ),
    array( 'data=> array(20,30,10,40), 'result=> TRUE ),
    array( 'data=> array(10,30,20,40), 'result=> TRUE ),
    array( 'data=> array(20,40,10,30), 'result=> TRUE ),
);


foreach ($tests as $test) {
    $foo = overlaps(
        $test['data'][0],
        $test['data'][1],
        $test['data'][2],
        $test['data'][3]
    );

    echo ($foo == $test['result'] ? "ok\n: "FAIL\n");
}


Update
Here is fremnet's version that works even if you get the start/end dates the wrong way around:
http://pastebin.com/f62002cb5

1 comment:

Anonymous said...

helpful, thanks!