Time Periods in .NET
I was working on a difficult problem last week at work. I had a list of times and I needed to find the overlapping periods (if any). Here's a simple example, if we have 3 periods of time:
- 3/24/2013 5:00am - 3/24/2013 7:00am
- 3/24/2013 6:15am - 3/24/2013 12:00pm
- 3/25/2013 10:00am - 3/25/2013 6:00pm
To add more complexity to the problem I was facing, there are three types of periods and we have to find overlaps in each. In other words, I needed to find overlapping times that occurred in Type A, Type B, and Type C. Which means I couldn't just throw all the times together and find overlaps because it might just be an overlap in Type A and Type C.
As you can tell, it became complicated, quickly. I spent an hour or so trying to figure out how to get it to work, and was struggling. I then found a great utility called Time Period Library for .NET. It's a great tool if you are building a reservation program to see if a room is available for selected times.
In my case, I imported the Time period Library from NuGet into my project (p.s. I love NuGet!). Then I declared a TimePeriodCollection for each type of period I need to use.
In my case, the three types of periods are optional, so there's another layer of complexity. Based on which type of periods are being used, I fill up the TimePeriodCollections.
Once the TimePeriodCollections are filled, I have to find the overlapping times. If we are only using one of the types, then it's a simple case of using ALL of the time periods (no need to use the Time Period library. If we are using two of the types, we only have to run the calculation once. Finally if we are using all three types, have to run the calculation twice.
First, we declare the variables that will hold the results:
First, I check to see if Type A is being used (if so, then we might be using all three types). If we aren't using type A, then we know we are using type B and C (remember, I check for the use of only one type prior to all of this).
From here, the variable overlapPeriods contains the range of start and end times that are overlapping. The Time Period Library is great for any date/time logic you might have for your .NET application.