I am working on an algorithm to calculate a continuous overlap of multiple date ranges. It also needs to have a set number of times that it overlaps. For the example image below, I need 3 dates to overlap continuously. The valid overlapping dates would be Aug 20 - Aug 23, as Aug 24 only has 2 overlapping.
I have attempted many approaches including looping through all dates and comparing each one indivually with the next. That code looks like this.
Here is a .net fiddle for better visualization: https://dotnetfiddle.net/x3LfHR#.
private bool Compare(CompareDate a, CompareDate b)
{
DateTime? tStartA = a.ActiveDate;
DateTime? tEndA = a.ExpireDate;
DateTime? tStartB = b.ActiveDate;
DateTime? tEndB= b.ExpireDate;
bool overlap = (tStartA <= tEndB || tEndB == null) && (tStartB <= tEndA || tEndA == null);
DateTime? overlapStart = null;
DateTime? overlapEnd = null;
if (overlap)
{
//Find maximum start date.
overlapStart = (tStartA >= tStartB) ? tStartA : tStartB;
//Find Min End date between the two
overlapEnd = (tEndA <= tEndB) ? tEndA : tEndB;
if (overlapStart > this.overlapStart || this.overlapStart == null)
{
this.overlapStart = overlapStart;
}
if (overlapEnd < this.overlapEnd || this.overlapEnd == null)
{
this.overlapEnd = overlapEnd;
}
However, this approach makes it tricky to figure out continuous overlap dates. I have attempted to use the .Net Time period library at https://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET, but its not relevant in my case. Any help is appreciated.