Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: .NET
Expertise: Advanced
Sep 10, 2009

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;
}
Chad Juliano
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap