Check if a date range is within a date range

前端 未结 8 2097
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 06:01

I have the following class:

public class Membership
{
    public DateTime StartDate { get; set; }
    public DateTime? EndDate { get; set; } // If null then          


        
相关标签:
8条回答
  • 2020-12-09 06:44

    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;
    }
    
    0 讨论(0)
  • 2020-12-09 06:47

    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);
    
    0 讨论(0)
提交回复
热议问题