Getting Overlapping Start and End Date

前端 未结 4 1457
情书的邮戳
情书的邮戳 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:48

    One method would be to make use of the Rectangle class to calculate intersects. So the procedure would be to create a rectangle for each date range then use the Rectangle.Intersect( ) method.

    0 讨论(0)
  • 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();    
    
    0 讨论(0)
  • 2021-01-28 10:04

    Something like this (not tested sorry):

    return bookedPeriods.Where(
        b => (b.StartDate > startDate && b.StartDate < endDate) ||
         (b.EndDate> startDate && b.EndDate < endDate) ||
         (b.StartDate < startDate && b.EndDate > endDate)
    ).ToList()
    
    0 讨论(0)
  • 2021-01-28 10:07

    this piece of LINQ might help:

    var overlappedPeriods = bookedPeriods.Where(p=>p.EndDate > startDate && p.StartDate < endDate);
    

    then transform the results accordingly to your OverlappedPeriod class

    0 讨论(0)
提交回复
热议问题