Calculate the number of weekdays between two dates in C#

Viewed 32335

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 but I can't seem to find a conclusive correct answer that abides by the following:

  1. The total should be inclusive, so GetNumberOfWeekdays(new DateTime(2009,11,30), new DateTime(2009,12,4)) should equal 5, that's Monday to Friday.
  2. Should allow for leap days
  3. does NOT just iterate through all the dates between whilst counting the weekdays.

I've found a similar question with an answer that comes close but is not correct

11 Answers
        public static int GetWeekDays(DateTime startDay, DateTime endDate, bool countEndDate = true)
        {
            var daysBetween = (int)(endDate - startDay).TotalDays;
            daysBetween = countEndDate ? daysBetween += 1 : daysBetween;
            return Enumerable.Range(0, daysBetween).Count(d => !startDay.AddDays(d).DayOfWeek.In(DayOfWeek.Saturday, DayOfWeek.Sunday));
        }

        public static bool In<T>(this T source, params T[] list)
        {
            if (null == source)
            {
                throw new ArgumentNullException("source");
            }
            return list.Contains(source);
        }

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> { DayOfWeek.Saturday, DayOfWeek.Sunday });


    /// <summary>
    /// For better accuracy make sure <paramref name="startDate"/> and <paramref name="endDate"/> have the same time zone.
    /// This is only really useful if we use <paramref name="daysOfWeekToExclude"/> - otherwise the computation is trivial.
    /// </summary>
    /// <param name="startDate"></param>
    /// <param name="endDate"></param>
    /// <param name="daysOfWeekToExclude"></param>
    /// <returns></returns>
    public static int DaysUntill(this DateTime startDate, DateTime endDate, IEnumerable<DayOfWeek> daysOfWeekToExclude = null)
    {
        if (startDate >= endDate) return 0;
        daysOfWeekToExclude = daysOfWeekToExclude?.Distinct() ?? new List<DayOfWeek>();

        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;
    }
Related