Alex Rivera | Logout

Calculate the number of weekdays between two dates in C#

Asked 2009-11-30T14:35:09.093
26

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

c#
Edit
Report

1 Answer

1
  public static List<DateTime> Weekdays(DateTime startDate, DateTime endDate)
  {
      if (startDate > endDate)
      {
          Swap(ref startDate, ref endDate);
      }
      List<DateTime> days = new List<DateTime>();

      var ts = endDate - startDate;
      for (int i = 0; i < ts.TotalDays; i++)
      {
          var cur = startDate.AddDays(i);
          if (cur.DayOfWeek != DayOfWeek.Saturday && cur.DayOfWeek != DayOfWeek.Sunday)
              days.Add(cur);
          //if (startingDate.AddDays(i).DayOfWeek != DayOfWeek.Saturday || startingDate.AddDays(i).DayOfWeek != DayOfWeek.Sunday)
          //yield return startingDate.AddDays(i);
      }
      return days;
  }

And swap dates

  private static void Swap(ref DateTime startDate, ref DateTime endDate)
  {
      object a = startDate;
      startDate = endDate;
      endDate = (DateTime)a;
  }
answered 2013-06-07T21:40:25.300

Your Answer