Calculate the number of weekdays between two dates in C#

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

      public static List Weekdays(DateTime startDate, DateTime endDate)
      {
          if (startDate > endDate)
          {
              Swap(ref startDate, ref endDate);
          }
          List days = new List();
    
          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;
      }
    

提交回复
热议问题