Calculate the number of business days between two dates?

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

    I think none of the above answers are actually correct. None of them solves all the special cases such as when the dates starts and ends on the middle of a weekend, when the date starts on a Friday and ends on next Monday, etc. On top of that, they all round the calculations to whole days, so if the start date is in the middle of a saturday for example, it will substract a whole day from the working days, giving wrong results...

    Anyway, here is my solution that is quite efficient and simple and works for all cases. The trick is just to find the previous Monday for start and end dates, and then do a small compensation when start and end happens during the weekend:

    public double WorkDays(DateTime startDate, DateTime endDate){
            double weekendDays;
    
            double days = endDate.Subtract(startDate).TotalDays;
    
            if(days<0) return 0;
    
            DateTime startMonday = startDate.AddDays(DayOfWeek.Monday - startDate.DayOfWeek).Date;
            DateTime endMonday = endDate.AddDays(DayOfWeek.Monday - endDate.DayOfWeek).Date;
    
            weekendDays = ((endMonday.Subtract(startMonday).TotalDays) / 7) * 2;
    
            // compute fractionary part of weekend days
            double diffStart = startDate.Subtract(startMonday).TotalDays - 5;
            double diffEnd = endDate.Subtract(endMonday).TotalDays - 5;
    
            // compensate weekenddays
            if(diffStart>0) weekendDays -= diffStart;
            if(diffEnd>0) weekendDays += diffEnd;
    
            return days - weekendDays;
        }
    

提交回复
热议问题