Add or Subtract Weekdays from a Date: Simple Function
Adding or subtracting weekdays from a date requires skipping Saturday and Sunday during the count. Pass your start date and a positive or negative integer representing weekday steps into a loop that increments one day at a time, checks whether the resulting day falls on a weekend, and only counts it when it does not, returning the final date.
Below is a simple function to add or subtract a number of weekdays to a specified date.
/// <summary>
/// Takes a reference date and add or subtracts a specified number of weekdays.
/// </summary>
/// <param name="date">The reference date.</param>
/// <param name="offset">The number of days to offset by.</param>
/// <returns>The reference date plus or minus the specified number of weekdays.</returns>
private DateTime AddWeekDays( DateTime date, int offset)
{
int daysAdded = 0;
int addDay = 1;
if (offset < 0)
{
addDay = -1;
}
DateTime result = date;
do
{
if (daysAdded == offset)
{
break;
}
if (result.DayOfWeek != DayOfWeek.Saturday && result.DayOfWeek != DayOfWeek.Sunday)
{
daysAdded = daysAdded + addDay;
}
result = result.AddDays(addDay);
} while (true);
return result;
}