If I have two date ranges (e.g. May 1 - May 31 and May 23 - June 5) what would be the best way to find out how many days the two periods overlap in PHP (so it would return 9)? Is there a way to do this using DatePeriod objects?
Edit to (hopefully) clarify my question:
Basically I want a function that, given any two date ranges, will return the number of days that are common between both date ranges. If there is an overlap it will return the number of overlapping days, otherwise it will return 0. I thought this could be done by making an array of dates for each range, looping through them to find identical dates, and using a variable to count the number of matches - but I am looking for something more elegant.
Thanks to @phpisuber01 and Determine Whether Two Date Ranges Overlap for providing the basic logic here. The four variables need to be DateTime objects:
function datesOverlap($start_one,$end_one,$start_two,$end_two) {
if($start_one <= $end_two && $end_one >= $start_two) { //If the dates overlap
return min($end_one,$end_two)->diff(max($start_two,$start_one))->days + 1; //return how many days overlap
}
return 0; //Return 0 if there is no overlap
}