I have the following class:
public class Membership
{
public DateTime StartDate { get; set; }
public DateTime? EndDate { get; set; } // If null then
I came up with the following method to check if dates overlap, it may not be the most effecient way but i hope this helps..
public static bool DateRangesOverlap(DateTime startDateA, DateTime endDateA, DateTime startDateB, DateTime endDateB)
{
var allDatesA = new List<DateTime>();
var allDatesB = new List<DateTime>();
for (DateTime date = startDateA; date <= endDateA; date = date.AddDays(1))
{
allDatesA.Add(date);
}
for (DateTime date = startDateB; date <= endDateB; date = date.AddDays(1))
{
allDatesB.Add(date);
}
var isInRange = false;
foreach (var date in allDatesA)
{
var existsInAllDatesB = allDatesB.Any(x => x == date);
if (existsInAllDatesB)
{
isInRange = true;
break;
}
}
return isInRange;
}
Basically, a date range overlaps another if any of its endings are within the other range, or vice versa.
static bool AllowedToAdd(List<Membership> membershipList, Membership newItem)
{
return !membershipList.Any(m =>
(m.StartDate < newItem.StartDate &&
newItem.StartDate < (m.EndDate ?? DateTime.MaxValue))
||
(m.StartDate < (newItem.EndDate ?? DateTime.MaxValue) &&
(newItem.EndDate ?? DateTime.MaxValue) <= (m.EndDate ?? DateTime.MaxValue))
||
(newItem.StartDate < m.StartDate &&
m.StartDate < (newItem.EndDate ?? DateTime.MaxValue))
||
(newItem.StartDate < (m.EndDate ?? DateTime.MaxValue) &&
(m.EndDate ?? DateTime.MaxValue) <= (newItem.EndDate ?? DateTime.MaxValue))
);
}
With the usage:
if (AllowedToAdd(membershipList, newItem))
membershipList.Add(newItem);