Calculate the number of weekdays between two dates in C#

c#

Solution

From this link:

    public static int Weekdays(DateTime dtmStart, DateTime dtmEnd)
    {
        // This function includes the start and end date in the count if they fall on a weekday
        int dowStart = ((int)dtmStart.DayOfWeek == 0 ? 7 : (int)dtmStart.DayOfWeek);
        int dowEnd = ((int)dtmEnd.DayOfWeek == 0 ? 7 : (int)dtmEnd.DayOfWeek);
        TimeSpan tSpan = dtmEnd - dtmStart;
        if (dowStart <= dowEnd)
        {
            return (((tSpan.Days / 7) * 5) + Math.Max((Math.Min((dowEnd + 1), 6) - dowStart), 0));
        }
        return (((tSpan.Days / 7) * 5) + Math.Min((dowEnd + 6) - Math.Min(dowStart, 6), 5));
    }


  [1]: http://www.eggheadcafe.com/community/aspnet/2/44982/how-to-calculate-num-of-w.aspx

Tests (each test returns 5):

    int ndays = Weekdays(new DateTime(2009, 11, 30), new DateTime(2009, 12, 4));
    System.Console.WriteLine(ndays);

    // leap year test
    ndays = Weekdays(new DateTime(2000, 2,27), new DateTime(2000, 3, 5));
    System.Console.WriteLine(ndays);

    // non leap year test
    ndays = Weekdays(new DateTime(2007, 2, 25), new DateTime(2007, 3, 4));
    System.Console.WriteLine(ndays);

Problem

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: - 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. - Should allow for leap days - 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

Original source

Related problems