Calculate the number of business days between two dates?

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

    Here is an helper function I wrote for that task.
    it also returns the count of weekends via the out parameter.
    if you wish you can customize the "weekend" days in run time for countries that use different weekend days or to include holidays trough the weekendDays[] optional parameter :

    public static int GetNetworkDays(DateTime startDate, DateTime endDate,out int totalWeekenDays, DayOfWeek[] weekendDays = null)
    {
        if (startDate >= endDate)
        {
            throw new Exception("start date can not be greater then or equel to end date");
        }
    
        DayOfWeek[] weekends = new DayOfWeek[] { DayOfWeek.Sunday, DayOfWeek.Saturday };
        if (weekendDays != null)
        {
            weekends = weekendDays;
        }
    
        var totaldays = (endDate - startDate).TotalDays + 1; // add one to include the first day to
        var counter = 0;
        var workdaysCounter = 0;
        var weekendsCounter = 0;
    
        for (int i = 0; i < totaldays; i++)
        {
    
            if (weekends.Contains(startDate.AddDays(counter).DayOfWeek))
            {
                weekendsCounter++;
            }
            else
            {
                workdaysCounter++;
            }
    
            counter++;
        }
    
        totalWeekenDays = weekendsCounter;
        return workdaysCounter;
    }
    

提交回复
热议问题