C#: Adding working days from a cetain date

前端 未结 6 1296
不知归路
不知归路 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:54

    Is an old post but somebody could be interested in an extension that handles also negative days. (I've reworked @Jon answer)

        public static DateTime AddWeekDays(this DateTime start, int days)
        {
            int direction = Math.Sign(days);
    
            int completeWeeks = days / 5;
            int remaining = days % 5;
    
            DateTime end = start.AddDays(completeWeeks * 7);
    
            for (int i = 0; i < remaining * direction; i++)
            {
                end = end.AddDays(direction * 1);
                while (!IsWeekDay(end))
                {
                    end = end.AddDays(direction * 1);
                }
            }
            return end;
        }
    
        private static bool IsWeekDay(DateTime date)
        {
            DayOfWeek day = date.DayOfWeek;
            return day != DayOfWeek.Saturday && day != DayOfWeek.Sunday;
        }
    

提交回复
热议问题