Comparing Date Ranges For Overlap
I often find myself writing logic to compare two date ranges to see if they overlap. In fact, I’ve done this enough times that I thought it was worth capturing in a blog post to save myself the time of having to figure it out next time. Hopefully you, dear reader, will also find it useful.
TL;DR
If you don’t need to understand the reason why, no need to read on. Just use this logic:
(StartA <= EndB) and (StartB <= EndA)
The Details
There are two different conditions that could make for non-overlapping ranges:
Condition 1:
Range B ends before Range A starts, which we could write as:
StartA > EndB
Condition 2:
Range A ends before Range B starts, which we could write as:
StartB > EndA
So, two ranges overlap if neither Condition 1 or Condition 2 is true, which we can write like this:
NOT ((StartA > EndB) OR (StartB > EndA))
Now, we know that “not (A or B)” is the same as “(not A) and (not B)”, so to simplify, we can write the above as:
(NOT (StartA > EndB)) and (NOT (StartB > EndA))
Finally, we can remove the NOTs by reversing the < and > comparisons, where, for example NOT > is the same as <=.
(StartA <= EndB) and (StartB <= EndA)