Calculate the number of business days between two dates?

后端 未结 30 1670
悲&欢浪女
悲&欢浪女 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:41

    Yet another approach for calculating business days, not considering holidays, but taking into account the time of day returning a fractional amount of days:

    public static double GetBusinessDays(DateTime startD, DateTime endD)
    {
        while (IsWeekend(startD))
            startD = startD.Date.AddDays(1);
    
        while (IsWeekend(endD))
            endD = endD.Date.AddDays(-1);
    
        var bussDays = (endD - startD).TotalDays -
            (2 * ((int)(endD - startD).TotalDays / 7)) -
            (startD.DayOfWeek > endD.DayOfWeek ? 2 : 0);
    
        return bussDays;
    }
    
    public static bool IsWeekend(DateTime d)
    {
        return d.DayOfWeek == DayOfWeek.Saturday || d.DayOfWeek == DayOfWeek.Sunday;
    }
    

    You can fiddle with it here: https://rextester.com/ASHRS53997

提交回复
热议问题