PHP: Get intersecting dates between 2 date ranges
Here is a small code snippet that will give you intersecting dates between 2 date ranges. Say, for example, you have 2 date ranges, 1-Jan-2011 to 31-Mar-2011 and 23-Feb-2011 to 4-May-2011. This function will give you 23-Feb-2011 to 31-Mar-2011 as result.
Here is the code:
$a1 = "2011-01-01";
$a2 = "2011-03-31";
$b1 = "2011-02-23";
$b2 = "2011-05-04";
$intersection = getIntersection($a1,$a2,$b1,$b2);
if($intersection === false)
{
echo 'No intersecting dates found';
}
else
{
echo 'From '.date('d-M-Y', $intersection['start']).' till '.date('d-M-Y', $intersection['end']);
}
function getIntersection($a1,$a2,$b1,$b2)
{
$a1 = strtotime($a1);
$a2 = strtotime($a2);
$b1 = strtotime($b1);
$b2 = strtotime($b2);
if($b1 > $a2 || $a1 > $b2 || $a2 < $a1 || $b2 < $b1)
{
return false;
}
$start = $a1 < $b1 ? $b1 : $a1;
$end = $a2 < $b2 ? $a2 : $b2;
return array('start' => $start, 'end' => $end);
}
Above will show the following on browser :
From 23-Feb-2011 till 31-Mar-2011
If the 2 date ranges have any intersecting dates, an array will be returned which will have start and end elements that represent the beginning and end of intersecting range. Set of dates given below will return false as there are no intersecting dates.
$a1 = "2011-01-01"; $a2 = "2011-03-31"; $b1 = "2011-04-23"; $b2 = "2011-05-04"; $intersection = getIntersection($a1,$a2,$b1,$b2);
This will show
No intersecting dates found
The code is self-explanatory. As you can see, first we have used php function strtotime to convert all dates to timestamps. Then we can compare them easily. This way you can use whatever(allowed) date format you wish.
