Adding Workdays to a Date

Adding Workdays to a Date

This example adds the days of the week and the weeks separately. You never iterate over the loop more then four times regardless of the number of days being added.

After adding the day of the week, simply add seven days for every five business days to calculate the final result. Note that the function works for both future and past dates:

public DateTime AddWorkingDays(DateTime dtFrom, int nDays){    int nDirection = 1;    if (nDays < 0) { nDirection = -1; }    int nWeekday = nDays % 5;    while(nWeekday != 0)    {        dtFrom = dtFrom.AddDays(nDirection);        if (dtFrom.DayOfWeek != DayOfWeek.Saturday            && dtFrom.DayOfWeek != DayOfWeek.Sunday)        {            nWeekday -= nDirection;        }    }    int nDayweek = (nDays / 5) * 7;    dtFrom = dtFrom.AddDays(nDayweek);    return dtFrom;}
See also  Essential Measures for Safeguarding Your Digital Data

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist