Adding Days to a Date but Excluding Weekends

前端 未结 11 2201
萌比男神i
萌比男神i 2020-12-01 15:47

Given a date how can I add a number of days to it, but exclude weekends. For example, given 11/12/2008 (Wednesday) and adding five will result in 11/19/2008 (Wednesday) rath

11条回答
  •  广开言路
    2020-12-01 16:32

    Without over-complicating the algorithm, you could just create an extension method like this:

    public static DateTime AddWorkingDays(this DateTime date, int daysToAdd)
    {
        while (daysToAdd > 0)
        {
            date = date.AddDays(1);
    
            if (date.DayOfWeek != DayOfWeek.Saturday && date.DayOfWeek != DayOfWeek.Sunday)
            {
                daysToAdd -= 1;
            }
        }
    
        return date;
    }
    

提交回复
热议问题