Calculate the number of weekdays between two dates in C#

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

    I needed positive / negatives (not absolute values) so here's how I solved it:

        public static int WeekdayDifference(DateTime StartDate, DateTime EndDate)
        {
            DateTime thisDate = StartDate;
            int weekDays = 0;
            while (thisDate != EndDate)
            {
                if (thisDate.DayOfWeek != DayOfWeek.Saturday && thisDate.DayOfWeek != DayOfWeek.Sunday) { weekDays++; }
                if (EndDate > StartDate) { thisDate = thisDate.AddDays(1); } else { thisDate = thisDate.AddDays(-1); }
            }
    
            /* Determine if value is positive or negative */
            if (EndDate > StartDate) {
                return weekDays;
            }
            else
            {
                return weekDays * -1;
            }
        }
    

提交回复
热议问题