C#: Adding working days from a cetain date

前端 未结 6 1299
不知归路
不知归路 2021-02-14 18:10

I have trouble doing this. I\'m creating a method that add working days on a specific date. for example, I want to add 3 working days to sept 15, 2010 (Wednesday), the method wo

6条回答
  •  爱一瞬间的悲伤
    2021-02-14 18:51

    Here's what you need :

    Updated :

    public static DateTime AddWeekdays(DateTime start, int days)
        {
            int remainder = days % 5;
            int weekendDays = (days / 5) * 2;
    
            DateTime end = start.AddDays(remainder);
    
            if (start.DayOfWeek == DayOfWeek.Saturday && days > 0)
            {
                // fix for saturday.
                end = end.AddDays(-1);
            }
    
            if (end.DayOfWeek == DayOfWeek.Saturday && days > 0)
            {
                // add two days for landing on saturday
                end = end.AddDays(2);
            }
            else if (end.DayOfWeek < start.DayOfWeek)
            {
                // add two days for rounding the weekend
                end = end.AddDays(2);
            }
    
            // add the remaining days
            return end.AddDays(days + weekendDays - remainder);
        }
    

提交回复
热议问题