Getting Overlapping Start and End Date

前端 未结 4 1456
情书的邮戳
情书的邮戳 2021-01-28 09:13

Given a DateRange I need to return a list of Start and EndDates that overlaps the given period.

what is the best way to do it? Thanks for your time in advance.

4条回答
  •  清酒与你
    2021-01-28 09:55

    Are you looking for dates that are completely within the provided period, or only partially?

    Completely within the range:

    var overlapped = 
        from period in bookedPeriods
        where period.StartDate >= startDate && period.EndDate <= endDate
        select new OverlappedPeriod { StartDate = period.StartDate, EndDate = period.EndDate };
    overlappedPeriods = overlapped.ToList();    
    

    Partially overlapping:

    var overlapped = 
        from period in bookedPeriods
        where (period.StartDate >= startDate && period.EndDate <= endDate)
            || (period.EndDate >= startDate && period.EndDate <= endDate)
            || (period.StartDate <= startDate && period.EndDate >= startDate)
            || (period.StartDate <= startDate && period.EndDate >= endDate)
        select new OverlappedPeriod 
        {
            StartDate = new DateTime(Math.Max(period.StartDate.Ticks, startDate.Ticks)),
            EndDate = new DateTime(Math.Min(period.EndDate.Ticks, endDate.Ticks))
        };
    
    overlappedPeriods = overlapped.ToList();    
    

提交回复
热议问题