Calculate the number of business days between two dates?

后端 未结 30 1808
悲&欢浪女
悲&欢浪女 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:39

    public static int CalculateBusinessDaysInRange(this DateTime startDate, DateTime endDate, params DateTime[] holidayDates)
    {
        endDate = endDate.Date;
        if(startDate > endDate)
            throw new ArgumentException("The end date can not be before the start date!", nameof(endDate));
        int accumulator = 0;
        DateTime itterator = startDate.Date;
        do 
        {
            if(itterator.DayOfWeek != DayOfWeek.Saturday && itterator.DayOfWeek != DayOfWeek.Sunday && !holidayDates.Any(hol => hol.Date == itterator))
            { accumulator++; }
        } 
        while((itterator = itterator.AddDays(1)).Date <= endDate);
        return accumulator
    }
    

    I'm only posting this because despite all of the excellent answers that have been given, none of the math made sense to me. This is definitely a KISS method that should work and be fairly maintainable. Granted if you are calculating ranges that are greater than 2-3 months this will not be the most effective way. We simply determine if it is a Saturday or Sunday or the date is a given holiday date. If it's not we add a business day. If it is then everything is fine.

    I'm sure this could be even more so simplified with LINQ, but this way is much easier to understand.

提交回复
热议问题