两个日期范围之间相交的天数

Bor*_*ary 10 c# asp.net

有人想知道如何最好地计算两个日期范围之间相交的天数吗?

Ben*_*gel 13

这是我写的一个小方法来计算这个.

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;
}
Run Code Online (Sandbox Code Playgroud)


Tre*_*edd 5

获得一个新的范围,由开始的晚期和结束的早期定义,并确定自该新范围中每天的纪元开始以来的天数.

不同之处在于交叉路口的天数.只接受正值.

编辑时考虑范围而不是个别日期.