Calculate the number of business days between two dates?

后端 未结 30 1672
悲&欢浪女
悲&欢浪女 2020-11-22 14:54

In C#, how can I calculate the number of business (or weekdays) days between two dates?

30条回答
  •  情深已故
    2020-11-22 15:50

    Since I can't comment. There is one more issue with the accepted solution where bank holidays are subtracted even when they are situated in the weekend. Seeing how other input is checked, it is only fitting that this is as well.

    The foreach should therefore be:

        // subtract the number of bank holidays during the time interval
        foreach (DateTime bankHoliday in bankHolidays)
        {
            DateTime bh = bankHoliday.Date;
    
            // Do not subtract bank holidays when they fall in the weekend to avoid double subtraction
            if (bh.DayOfWeek == DayOfWeek.Saturday || bh.DayOfWeek == DayOfWeek.Sunday)
                    continue;
    
            if (firstDay <= bh && bh <= lastDay)
                --businessDays;
        }
    

提交回复
热议问题