Calculate the number of business days between two dates?

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

    I know this question is already solved, but I thought I could provide a more straightforward-looking answer that may help other visitors in the future.

    Here's my take at it:

    public int GetWorkingDays(DateTime from, DateTime to)
    {
        var dayDifference = (int)to.Subtract(from).TotalDays;
        return Enumerable
            .Range(1, dayDifference)
            .Select(x => from.AddDays(x))
            .Count(x => x.DayOfWeek != DayOfWeek.Saturday && x.DayOfWeek != DayOfWeek.Sunday);
    }
    

    This was my original submission:

    public int GetWorkingDays(DateTime from, DateTime to)
    {
        var totalDays = 0;
        for (var date = from; date < to; date = date.AddDays(1))
        {
            if (date.DayOfWeek != DayOfWeek.Saturday
                && date.DayOfWeek != DayOfWeek.Sunday)
                totalDays++;
        }
    
        return totalDays;
    }
    

提交回复
热议问题