Calculate the number of weekdays between two dates in C#

前端 未结 11 2237
温柔的废话
温柔的废话 2020-12-03 16:59

How can I get the number of weekdays between two given dates without just iterating through the dates between and counting the weekdays?

Seems fairly straightforward

11条回答
  •  死守一世寂寞
    2020-12-03 17:45

    This is an old question but I figured I would share a more flexible answer which allows to removes any day of the week.

    I tried to keep the code clean and easy to read while remaining efficient by only looping through 6 days max.

    So for the OP you can use it like this:

        myDate.DaysUntill(DateTime.UtcNow, new List { DayOfWeek.Saturday, DayOfWeek.Sunday });
    
    
        /// 
        /// For better accuracy make sure  and  have the same time zone.
        /// This is only really useful if we use  - otherwise the computation is trivial.
        /// 
        /// 
        /// 
        /// 
        /// 
        public static int DaysUntill(this DateTime startDate, DateTime endDate, IEnumerable daysOfWeekToExclude = null)
        {
            if (startDate >= endDate) return 0;
            daysOfWeekToExclude = daysOfWeekToExclude?.Distinct() ?? new List();
    
            int nbOfWeeks = (endDate - startDate).Days / 7;
            int nbOfExtraDays = (endDate - startDate).Days % 7;
    
            int result = nbOfWeeks * (7 - daysOfWeekToExclude.Count());
    
            for (int i = 0; i < nbOfExtraDays; i++)
            {
                if (!daysOfWeekToExclude.Contains(startDate.AddDays(i + 1).DayOfWeek)) result++;
            }
            return result;
        }
    

提交回复
热议问题