-1
class Period {
   public DateTime Start { get; set; }
   public DateTime End { get; set; } 
}

I'm having difficulty with boolean logic of comparing two Period objects

Suppose in DB I have the following Period object.

var periodInDb = new Period { 
   Start = DateTime.ParseExact("2022-12-18", "yyyy-MM-dd", CultureInfo.InvariantCulture);
   End = DateTime.ParseExact("2023-01-11", "yyyy-MM-dd", CultureInfo.InvariantCulture);
};

I want to only add a new period if it doesn't fall in between the period above.

I have written out on paper some type of scenario dates that might get added, I might have missed some scenarios:

Start: 2022/12/18
End: 2023/01/11

Some scenario dates:

Start: 2022/12/19 ✔️
End: 2023/01/10 ❌
------------------
❌ Don't add because end date falls between between 2022/12/18 - 2023/01/11


Start: 2022/12/19 ✔️
End: 2023/01/12 ✔️
------------------
❌ Don't add because start date falls between 2022/12/18 - 2023/01/11


Start: 2022/12/17 ✔️
End: 2023/01/12 ✔️
------------------
❌ Don't add because part of start date and end date falls outside of 2022/12/18 - 2023/01/11

Start: 2022/12/16 ✔️
End: 2023/12/17 ✔️
------------------
✔️ Add because start date and end date falls outside of 2022/12/18 - 2023/01/11

How would I know if a period falls outside of another period?

lunisolar
  • 137
  • 2
  • I'd suggest to use this library which makes this trival and keeps your code readable: https://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET – Tim Schmelter Jul 28 '21 at 15:50
  • `2022-13-18`? When is that? – Joel Coehoorn Jul 28 '21 at 15:51
  • @JoelCoehoorn I meant `2022-12-18` – lunisolar Jul 28 '21 at 15:53
  • 1
    Why is this question marked as duplicate, this is `date range compared to date range`, and not `date range compared to datetime`? – lunisolar Jul 28 '21 at 16:05
  • It is not the right duplicate, but it is a duplicate of [this (*Algorithm to detect overlapping periods*)](https://stackoverflow.com/questions/13513932/algorithm-to-detect-overlapping-periods) which was already marked as a duplicate of [that (*Determine Whether Two Date Ranges Overlap*)](https://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap) – Rafalon Jul 28 '21 at 16:09

1 Answers1

2
public bool HasOverlap(Period p1, Period p2)
{
    return p1.End >= p2.Start && p1.Start <= p2.End;
}
Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • This. Note that depending on OP's specs, inequalities could be strict, but the logic is good here – Rafalon Jul 28 '21 at 16:06