Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find overlapping dateperiods/date ranges in PHP? [closed]

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.

like image 444
Dustin Avatar asked Jan 07 '13 19:01

Dustin


People also ask

How can I tell if two date ranges overlap in PHP?

You can do this by swapping the ranges if necessary up front. Then, you can detect overlap if the second range start is: less than or equal to the first range end (if ranges are inclusive, containing both the start and end times); or. less than (if ranges are inclusive of start and exclusive of end).

How do you find overlapping time intervals?

1) Sort all intervals in increasing order of start time. This step takes O(nLogn) time. 2) In the sorted array, if start time of an interval is less than end of previous interval, then there is an overlap.

What are overlapping dates?

Overlapping date a day and month in any year during the deposit period, whose number is the same as the number of the day and month on which the deposit commencement date falls.


2 Answers

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
}
like image 65
Dustin Avatar answered Oct 12 '22 18:10

Dustin


Without any real information to base this on.. Here is a basic example of how to calculate a difference of days using the DateTime object.

$datetime1 = new DateTime('2013-05-23');
$datetime2 = new DateTime('2013-05-31');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days'); //returns 8 days

I assume you know how to convert your strings there into usable timestamps/formats.

like image 42
phpisuber01 Avatar answered Oct 12 '22 18:10

phpisuber01