Comparing Date Ranges For Overlap

2 Comments
dateranges

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:

 

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:

Condition 2:
Range A ends before Range B starts, which we could write as:

So, two ranges overlap if neither Condition 1 or Condition 2 is true, which we can write like this:

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:

Finally, we can remove the NOTs by reversing the < and > comparisons, where, for example NOT > is the same as <=.