Calculate the number of weekdays between two dates in C#

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

            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(this T source, params T[] list)
            {
                if (null == source)
                {
                    throw new ArgumentNullException("source");
                }
                return list.Contains(source);
            }
    

提交回复
热议问题