Calculate the number of business days between two dates?

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

    You just have to iterate through each day in the time range and subtract a day from the counter if its a Saturday or a Sunday.

        private float SubtractWeekend(DateTime start, DateTime end) {
            float totaldays = (end.Date - start.Date).Days;
            var iterationVal = totalDays;
            for (int i = 0; i <= iterationVal; i++) {
                int dayVal = (int)start.Date.AddDays(i).DayOfWeek;
                if(dayVal == 6 || dayVal == 0) {
                    // saturday or sunday
                    totalDays--;
                }
            }
            return totalDays;
        }
    

提交回复
热议问题