Tuesday, November 15, 2011

Test If Date Ranges Overlap

Test If Date Ranges Overlap

A commonly-used idiom for determining if one range of dates overlaps with another range of dates

Problem: Given two date ranges, each with start and end dates (and possibly times), how do you determine if the ranges overlap?

Solution:

Testing the range "start1 to end1" against the range "start2 to end2" is done by testing if...

	( start1 <= end2 and start2 <= end1 )
If TRUE, then the ranges overlap.

If the ranges do not include the "end" value itself, then use "<" instead of "<=" in the comparisons.

Important Assumption:

This assumes that start date <= end date in each range. This can also be stated as...

	( start1 <= end1 and start2 <= end2 )
For discussion of what to do if this is not true, see below.

Applicability: Is not limited to date/time comparisons; can also be used for ranges of numbers, names, and any other data type where ranges are meaningful.

Alternate Expression:

	not (end1 < start2 or end2 < start1)



The expression in brackets is true when one range is entirely to the left or right of the other. This condition is pretty easy to visualize. The ranges overlap if and only if it is false.
Implementation: See MartinFowler's RangePattern for implementation details. http://www.martinfowler.com/ap2/range.html

[CategoryPattern]

 

Check the original post http://c2.com/cgi/wiki?TestIfDateRangesOverlap for more information

No comments:

Post a Comment