Reputation: 51
In simple terms i have a date range object which stores a start/end date. I want to compare 2 date ranges for no overlap, but also allowing adjacent ranges where the first range end date is equal to the 2nd range start date.
Range 1 = 1/1/2016 10:00AM - 1/1/2016 10:30AM Range 2 = 1/1/2016 10:30AM - 1/1/2016 11:30AM
I've hada a few goes at creating a c# function but cant seem to get it working right.
Any help appreciated.
Upvotes: 0
Views: 109
Reputation: 51
Works great :-) thanks for your help. i've tested the above code with the following scenarios:
//this needs to take into the account the following range scenarios
//1. range1 start in range2 and finishes whenever
//2. range2 starts in range1 and finishes whenever
//3. range1 starts before range2 start and finishes in or after range2
//4. range2 starts before range1 start and finishes in or after range1
//5. range1 fully overlaps range2
//6. range2 fully overlaps range1
It should allow adjacent ranges where r1 end equals r2 start.
Upvotes: 0
Reputation: 19526
Something like this should work:
public class DateRange
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public bool Overlaps(DateRange otherRange)
{
if (StartDate < otherRange.EndDate && StartDate >= otherRange.StartDate)
return true;
if (otherRange.StartDate < EndDate && otherRange.StartDate >= StartDate)
return true;
if (EndDate > otherRange.StartDate && EndDate <= otherRange.EndDate)
return true;
if (otherRange.EndDate < StartDate && otherRange.EndDate >= EndDate)
return true;
return false;
}
Upvotes: 0