Count the number of weekdays between two dates in visual basic

后端 未结 6 1113
我寻月下人不归
我寻月下人不归 2021-01-14 21:48

I\'m a SQL guy, but I need a function to calculate the number of weekdays between two dates in VB.NET. I don\'t need to worry about holidays. My attempts unfortunately have

6条回答
  •  一生所求
    2021-01-14 22:20

    This may help someone else looking for this. This function doesn't loop day by day.

        public static double WorkDays(DateTime start, DateTime end)
        {
            var delta = end.AddDays(1) - start;
            var fullWeeks = (int)(delta.TotalDays / 7);
            var workDays = fullWeeks * 5;
    
            var partialWeekDays = delta.TotalDays % 7;
            if (partialWeekDays > 0)
            {
                var startWeekday = start.DayOfWeek;
                var endWeekday = end.DayOfWeek;
    
                if (startWeekday == DayOfWeek.Sunday || startWeekday == DayOfWeek.Saturday)
                    partialWeekDays--;
                if (startWeekday > DayOfWeek.Sunday && startWeekday < DayOfWeek.Saturday &&
                    startWeekday > endWeekday)
                    partialWeekDays--;
                if ((endWeekday == DayOfWeek.Sunday || endWeekday == DayOfWeek.Saturday) && endWeekday != startWeekday)
                    partialWeekDays--;
                if (endWeekday > DayOfWeek.Sunday && endWeekday < DayOfWeek.Saturday &&
                    startWeekday > endWeekday)
                    partialWeekDays--;
            }
    
            return workDays + partialWeekDays;
        }
    

提交回复
热议问题