Introduction
Before I wrote this class, I used to test for date range overlaps the hard way having to check each endpoint with lots of date comparisons. This way is much simpler and also more efficient.
Background
With testing for overlaps on any range of numbers/dates, there are three possibilities. These are shown below.
- Where the second interval (CD) overlaps on the beginning of the first (AB)
- Where the second interval (EF) overlaps on the end of the first (AB)
- Where the first interval (AB) exists inside the second (GH)
In the first case, you have to test if D lies between A and B. In the second, you have to test if E lies between A and B and in the third case, you have to test if both A and B lie between G and H. This leads to a lot of date comparisons to ensure you don't miss any case of an overlap.
There is a better way to test for overlaps using timespans which also enables you to test for more than two date ranges at a time. If you add up the total timespans of all the intervals AB, CD, EF and GH and compare this with the timespan of the minimum date (C) and maximum date (F), if the sum of the intervals is greater than the total timespan then there is an overlap, otherwise there is not.
In the image below, you can see that if you add up all the timespans of the intervals, this will be less than the total timespan and hence there is no overlap.
Using the Code
I have included two functions in the DateRange
class that perform the testing. The first only tests if there is an overlap at all and return true
if there is. The second returns a list of which date range pairs have a conflict.
Here are the prototypes:
public static bool HasOverlap(bool TestEndPoints, params DateRange[] Ranges);
public static IEnumerable<OverlapPairs> OverlapingRanges
(bool TestEndPoints, params DateRange[] Ranges);
The code snippet below will return true
.
DateRange.DateRange.HasOverlap(false,
new DateRange.DateRange(DateTime.Now,DateTime.Now.AddDays(1)),
new DateRange.DateRange(DateTime.Now.AddDays(-1),DateTime.Now.AddDays(2)));
Whereas this code snippet will return a list containing one Overlap Pairs of the first two date ranges. The third date range does not conflict at all.
DateRange.DateRange.OverlapingRanges(false,
new DateRange.DateRange(DateTime.Now,DateTime.Now.AddDays(1)),
new DateRange.DateRange(DateTime.Now.AddDays(-1),DateTime.Now.AddDays(2)),
new DateRange.DateRange(DateTime.Now.AddDays(-5),DateTime.Now.AddDays(-3)));
History
- 28th July, 2011 - Original version posted
- 2nd August, 2011 - Updated code to account for whitespace in more than 2 date ranges