计算两个日期之间的天数和小时数,考虑周末(仅限工作日)c#

时间:2014-08-22 10:33:13

标签: c# datetime

我试图这样做:

var startDate = DateTime.Now

var durationDays = 2

var expectedEndDate = startDate.AddDays(durationDays)

但如果在这些日子之间有周末,请将它们折扣为天数。因此,如果预期的结束日期在星期六,那么结束日期需要在下一个星期一。

4 个答案:

答案 0 :(得分:2)

根据您要添加的最大天数,您只需检查while循环中的某一天,然后通过AddDays添加另一天,只要expectedEndDate的当前日期{{1} 1}}一个周末。也许是这样的:

DateTime startDate = DateTime.Now
int durationDays = 2
DateTime expectedEndDate = startDate.AddDays(durationDays)
while( expectedEndDate.DayOfWeek == DayOfWeek.Saturday ||
       expectedEndDate.DayOfWeek == DayOfWeek.Sunday )
{
    expectedEndDate.AddDays( 1 );
}

如果您需要一个更灵活的解决方案来处理涵盖多个周末的较大日期差异,那么另一篇文章中的链接解决方案适合您(我试图保持简单: - ))。

答案 1 :(得分:0)

如果你正在检查更大的Timespan,你也可以使用这个效率更高的解决方案:Calculate the number of business days between two dates?

答案 2 :(得分:0)

试试这个:

        var startDate = DateTime.Now;
        var durationDays = 2;
        var expectedEndDate = startDate.AddDays(durationDays);

        if (expectedEndDate.DayOfWeek == DayOfWeek.Saturday)
        {
            expectedEndDate = expectedEndDate.AddDays(2);
        }
        else
        {
            if (expectedEndDate.DayOfWeek == DayOfWeek.Sunday)
            {
                expectedEndDate = expectedEndDate.AddDays(1);
            }
        }

答案 3 :(得分:0)

我试着提高@Gorgsenegger的答案:

    int iteration = 0;
        while (iteration < durationDays)
        {
            while (expectedEndDate.DayOfWeek != DayOfWeek.Saturday && expectedEndDate.DayOfWeek != DayOfWeek.Sunday)
            {
                expectedEndDate = expectedEndDate.AddDays(1);
                iteration++;
                if (iteration == durationDays) break;
            }
            if (iteration == durationDays) break;
            if (expectedEndDate.DayOfWeek == DayOfWeek.Saturday) expectedEndDate=expectedEndDate.AddDays(2);
            if (expectedEndDate.DayOfWeek == DayOfWeek.Sunday) expectedEndDate=expectedEndDate.AddDays(1);
        }
        if (expectedEndDate.DayOfWeek == DayOfWeek.Saturday)expectedEndDate= expectedEndDate.AddDays(2);
        if (expectedEndDate.DayOfWeek == DayOfWeek.Sunday) expectedEndDate=expectedEndDate.AddDays(1);

我认为此代码段会处理所有情况