-5

Time overlap with C#: checking 2 set of start and end date combination over lap checking?

  • "6:00 am" to "4:30 pm"
  • "8:29 am" to "4:30 pm"
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
  • Does this answer your question? [Algorithm to detect overlapping periods](https://stackoverflow.com/questions/13513932/algorithm-to-detect-overlapping-periods) – Ian Feb 05 '20 at 10:31

2 Answers2

0
private static bool CheckOverlap(TimeSpan startDate1, TimeSpan endDate1, TimeSpan startDate2, TimeSpan endDate2)
        {

            //TODO: Make sure startDate is lower than EndDate
              if (startDate2 < endDate1 && endDate2 > startDate1)
                return true;
            return false;
        }
  • So what if it's "11:30 pm" to "2:30 am" and "1:00 am" to "3:00" am"? The meetings clearly overlap, but your solution says they don't. – Frauke Feb 05 '20 at 10:35
0

You create custom class for stroing info about time periods, such as:

public class TimePeriod
{
  public DateTime Start { get; set; }
  public DateTime End { get; set; }

  public TimePeriod(DateTime start, DateTime end)
  {
    if( start > end)
      throw new InvalidArgumentException();
    Start = start;
    End = end;
  }

  public bool Overlaps(TimePeriod tp)
  {
    // it's enough for one's period start or end to fall between the other's start and end to overlap
    if ((Start > tp.Start && Start < tp.End ) ||
        (End > tp.Start && End < tp.End) ||
        (tp.Start > Start && tp.Start < End) ||
        (tp.End > Start && tp.End < End) )
      return true;
    else
      return false;
  }
}

Then the usage becomes extremely easy:

TimePeriod tp1 = new TimePeriod(dt1, dt2);
TimePeriod tp2 = new TimePeriod(dt3, dt4);

var overlaps = tp1.Overlaps(tp2);
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69