Easily finding if a date range contains another date range

Here's a quick tip. If you need to find out if a given date range is covered by another date range, this code does the trick.

Let's say you have an Event class with a Begin and End property and a SearchFilter with a Begin and End property. If you search for events between April 8 and April 12, you would want the following events to be included:

  • April 7 to April 9
  • April 11 to April 14
  • April 9 to April 10But you don't want the following events:

  • April 6 to April 7

  • April 13 to April 14

This is actually fairly easy, but requires you to compare the begin with the end and the end with the begin.

Confused? Here's some code:

public class SearchFilter  
{
    public DateTime Begin { get; set; }
    public DateTime End { get; set; }

    public bool Includes(Event evt)
    {
        return evt.End >= Begin && evt.Begin <= End;
    }
}

That's all there is to it. This image clarifies it a little more:

The blue block is the date range of the search filter. The green blocks will return true, as they are covered by the filter. The red blocks fall outside of the boundaries of the filter, so they will return false.