views:

88

answers:

4

Possible Duplicate:
Determine Whether Two Date Ranges Overlap

Say I have two objects, and each of these objects have a date ranges which is between its end date and start date, how do I figure out if there is any overlap between the two date ranges in the most efficient or quickest way.

I would like to do this using .NET 3.5 c#

+1  A: 

Check this out... Same principles apply

Charles Bretana
A: 

Whether this is the most efficient or quickest, I'm unsure, but this is how I would do it. If it turned out to be a bottleneck, then and only then would I look into optimising further:

You ensure that the first range starts earlier (or at the same time) by swapping the ranges if necessary.

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:

|----------------------|        range 1
|--->                           range 2 overlap
 |--->                          range 2 overlap
                       |--->    range 2 overlap
                        |--->   range 2 no overlap

The endpoint of the range 2 doesn't enter into it. So, in pseudo-code:

def doesOverlap (r1,r2):
    if r1.s > r2.s:
        swap r1, r2
    if r2.s > r1.e:
        return false
    return true

If the ranges are inclusive at the start and exclusive at the end, you just have to replace > with >= in the second if statement:

|----------------------|        range 1
|--->                           range 2 overlap
 |--->                          range 2 overlap
                       |--->    range 2 no overlap
                        |--->   range 2 no overlap

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.

paxdiablo
A: 

Check wether or not the Startdate or Enddate of the second object is in the range of the first object:

bool overlap = (y.Start > x.Start && y.Start < x.End) || (y.End > x.Start && y.End < x.End);

Femaref
x.Start: 2001-01-01, x.Stop: 2002-01-01, Y.Start: 1999-01-01, Y.Stop: 2001-06-01. Your function returns false. The correct answer is true.
Slartibartfast
bollocks. thanks.
Femaref
A: 

Martin Fowler would do it this way:

http://www.martinfowler.com/ap2/range.html

:-)

ThatSteveGuy