Given two date ranges, what is the simplest or most efficient way to determine whether the two date ranges overlap?
As an example, suppose we have ranges denoted by DateTime variables StartDate1
to EndDate1
and StartDate2
to EndDate2
.
Given two date ranges, what is the simplest or most efficient way to determine whether the two date ranges overlap?
As an example, suppose we have ranges denoted by DateTime variables StartDate1
to EndDate1
and StartDate2
to EndDate2
.
I believe that it is sufficient to say that the two ranges overlap if:
Here is a generic method that can be usefull locally.
Using Java util.Date, here what I did.
This was my javascript solution with moment.js:
Split the problem into cases then handle each case.
The situation 'two date ranges intersect' is covered by two cases - the first date range starts within the second, or the second date range starts within the first.
All the solutions that check a multitude of conditions based on where the ranges are in relation to one another can be greatly simplified by just ensuring that a specific range starts earlier! You ensure that the first range starts earlier (or at the same time) by swapping the ranges if necessary up front.
Then, you can detect overlap if the other 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).
Assuming inclusive at both ends, there's only four possibilities of which one is a non-overlap:
The endpoint of the range 2 doesn't enter into it. So, in pseudo-code:
This could be simplified even more into:
If the ranges are inclusive at the start and exclusive at the end, you just have to replace
>
with>=
in the secondif
statement (for the first code segment: in the second code segment, you'd use<
rather than<=
):You greatly limit the number of checks you have to make because you remove half of the problem space early by ensuring range 1 never starts after range 2.