Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count of days intersecting between two date ranges

Tags:

c#

asp.net

Would anyone have any ideas of how to best calculate the amount of days that intersect between two date ranges?

like image 298
BoredOfBinary Avatar asked Jun 03 '10 22:06

BoredOfBinary


2 Answers

Here's a little method I wrote to calculate this.

private static int inclusiveDays(DateTime s1, DateTime e1, DateTime s2, DateTime e2)
{
    // If they don't intersect return 0.
    if (!(s1 <= e2 && e1 >= s2))
    {
        return 0;
    }

    // Take the highest start date and the lowest end date.
    DateTime start = s1 > s2 ? s1 : s2;
    DateTime end = e1 > e2 ? e2 : e1;

    // Add one to the time range since its inclusive.
    return (int)(end - start).TotalDays + 1;
}
like image 56
Bengel Avatar answered Sep 28 '22 03:09

Bengel


Obtain a new range, defined by the later of the beginnings and the earlier of the ends, and determine the number of days since the beginning of the epoch for each day in that new range.

The difference is the number of days in the intersection. Accept only positive values.

Edited to take into account ranges instead of individual dates.

like image 41
TreDubZedd Avatar answered Sep 28 '22 03:09

TreDubZedd