I have seen numerous posts related to adding working days (excluding weekends) to a date parameter and I tried using a few from those. However, all the solutions I picked are failing in some scenarios.
below is the code I’m currently using:
private DateTime AddWorkingDays(DateTime dateValue, int noOfDays)
{
// determine if we are adding or subtracting the days
int nDirection = noOfDays < 0 ? -1 : 1;
// move ahead the day of week
int nWeekday = noOfDays % 5;
while (nWeekday != 0)
{
dateValue = dateValue.AddDays(nDirection);
if (dateValue.DayOfWeek != DayOfWeek.Saturday
&& dateValue.DayOfWeek != DayOfWeek.Sunday)
{
nWeekday -= nDirection;
}
}
// move ahead the number of weeks
int nDayweek = (noOfDays / 5) * 7;
dateValue = dateValue.AddDays(nDayweek);
return dateValue;
}
Example scenarios that fail:
Date: 24 Nov, 2012(saturday), No of days: 5 (or 10)
Result: 1 Dec, 2012 (or 8 Dec, 2012) when the expected result was 30 Nov, 2012
Fails for 25 Nov, 2012 also.. and similar scenarios I guess, where the input date falls on a weekend.
Can someone please help fixing such scenarios ? Or provide a better solution ?
Thank you
This implementation (actually quite similar to yours) gives the results you expect: