tags:

views:

2128

answers:

5

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) rather than 11/17/2008 (Monday).

I can think of a simple solution like looping through each day to add and checking to see if it is a weekend, but I'd like to see if there is something more elegant. I'd also be interested in any F# solution.

A: 

Given the number of the original day in the year D and original day in the week W and the number of workdays to add N, the next weekday number is

W + N % 5.

The next day in the year (with no wraparound check) is

D + ((N / 5) * 7) + N % 5).

This is assuming that you have integer division.

gnud
Why the down-vote? Does this yield an incorrect result?
DOK
I don't see any obvious flaw with my answer. Leaving a comment saying what's wrong would be helpful.
gnud
A: 
public DateTime AddBusinessDays(DateTime dt, int nDays)
{
    int weeks = nDays / 5;
    nDays %= 5;
    while(dt.DayOfWeek == DayOfWeek.Saturday || dt.DayOfWeek == DayOfWeek.Sunday)
     dt = dt.AddDays(1);

    while (nDays-- > 0)
    {
     dt = dt.AddDays(1);
     if (dt.DayOfWeek == DayOfWeek.Saturday)
      dt = dt.AddDays(2);
    }
    return dt.AddDays(weeks*7);
}
Jason Lepack
+2  A: 
int daysToAdd = weekDaysToAdd + ((weekDaysToAdd / 5) * 2) + (((origDate.DOW + (weekDaysToAdd % 5)) >= 5) ? 2 : 0);

To wit; the number of "real" days to add is the number of weekdays you're specifying, plus the number of complete weeks that are in that total (hence the weekDaysToAdd / 5) times two (two days in the weekend); plus a potential offset of two days if the original day of the week plus the number of weekdays to add "within" the week (hence the weekDaysToAdd mod 5) is greater than or equal to 5 (i.e. is a weekend day).

Note: this works assuming that 0 = Monday, 2 = Tuesday, ... 6 = Sunday. Also; this does not work on negative weekday intervals.

McWafflestix
+5  A: 

using Fluent DateTime http://fluentdatetime.codeplex.com/

        var dateTime = DateTime.Now.AddBusinessDays(4);
Simon
a better O(1) solution can be found here: http://stackoverflow.com/questions/1044688
Marco M.
A: 

Formula will be : Workday(date,no.of days,(weekday(1))) Try this .This will help and let me know it works or not at [email protected]