Adding Days to a Date but Excluding Weekends

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

    I created an extension that allows you to add or subtract business days. Use a negative number of businessDays to subtract. It seems to work in all cases.

    namespace Extensions.DateTime
    {
        public static class BusinessDays
        {
            public static System.DateTime AddBusinessDays(this System.DateTime source, int businessDays)
            {
                var dayOfWeek = businessDays < 0
                                    ? ((int)source.DayOfWeek - 12) % 7
                                    : ((int)source.DayOfWeek + 6) % 7;
    
                switch (dayOfWeek)
                {
                    case 6:
                        businessDays--;
                        break;
                    case -6:
                        businessDays++;
                        break;
                }
    
                return source.AddDays(businessDays + ((businessDays + dayOfWeek) / 5) * 2);
            }
        }
    }
    

    Example:

    using System;
    using System.Windows.Forms;
    using Extensions.DateTime;
    
    namespace AddBusinessDaysTest
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                label1.Text = DateTime.Now.AddBusinessDays(5).ToString();
                label2.Text = DateTime.Now.AddBusinessDays(-36).ToString();
            }
        }
    }
    

提交回复
热议问题