https://andrewbaker.ninja/wp-content/themes/twentysixteen/fonts/merriweather-plus-montserrat-plus-inconsolata.css

πŸ‘0views
Simple function to Add a number of weekdays to a date

CloudScale SEO — AI Article Summary
What it isThis article provides a function that adds or subtracts a specific number of weekdays (Monday through Friday) to any given date, automatically skipping weekends.
Why it mattersThis solves a common programming challenge where you need to calculate business days for scheduling, deadlines, or project timelines without manually accounting for weekends.
Key takeawayUse this function whenever you need to calculate business day dates while automatically excluding weekends from your calculations.

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;
}

Leave a Reply

Your email address will not be published. Required fields are marked *