Calculate the number of business days between two dates?

后端 未结 30 1693
悲&欢浪女
悲&欢浪女 2020-11-22 14:54

In C#, how can I calculate the number of business (or weekdays) days between two dates?

30条回答
  •  误落风尘
    2020-11-22 15:49

    Works and without loops

    This method doesn't use any loops and is actually quite simple. It expands the date range to full weeks since we know that each week has 5 business days. It then uses a lookup table to find the number of business days to subtract from the start and end to get the right result. I've expanded out the calculation to help show what's going on, but the whole thing could be condensed into a single line if needed.

    Anyway, this works for me and so I thought I'd post it here in case it might help others. Happy coding.

    Calculation

    • t : Total number of days between dates (1 if min = max)
    • a + b : Extra days needed to expand total to full weeks
    • k : 1.4 is number of weekdays per week, i.e., (t / 7) * 5
    • c : Number of weekdays to subtract from the total
    • m : A lookup table used to find the value of "c" for each day of the week

    Culture

    Code assumes a Monday to Friday work week. For other cultures, such as Sunday to Thursday, you'll need to offset the dates prior to calculation.

    Method

    public int Weekdays(DateTime min, DateTime max) 
    {       
            if (min.Date > max.Date) throw new Exception("Invalid date span");
            var t = (max.AddDays(1).Date - min.Date).TotalDays;
            var a = (int) min.DayOfWeek;
            var b = 6 - (int) max.DayOfWeek;
            var k = 1.4;
            var m = new int[]{0, 0, 1, 2, 3, 4, 5}; 
            var c = m[a] + m[b];
            return (int)((t + a + b) / k) - c;
    }
    

提交回复
热议问题