Calculate the number of weekdays between two dates in C#

前端 未结 11 2242
温柔的废话
温柔的废话 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:37

    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);
    

提交回复
热议问题