Adding Days to a Date but Excluding Weekends

前端 未结 11 2185
萌比男神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:18

    I would use this extension, remember since it is an extension method to put it in a static class.

    Usage:

    var dateTime = DateTime.Now.AddBusinessDays(5);
    

    Code:

    namespace ExtensionMethods
    {
        public static class MyExtensionMethods
        {
            public static DateTime AddBusinessDays(this DateTime current, int days)
            {
                var sign = Math.Sign(days);
                var unsignedDays = Math.Abs(days);
                for (var i = 0; i < unsignedDays; i++)
                {
                    do
                    {
                        current = current.AddDays(sign);
                    } while (current.DayOfWeek == DayOfWeek.Saturday ||
                             current.DayOfWeek == DayOfWeek.Sunday);
                }
                return current;
            }
        }
    }
    

    Source:

    https://github.com/FluentDateTime/FluentDateTime/blob/master/src/FluentDateTime/DateTime/DateTimeExtensions.cs

提交回复
热议问题