Goal:
Find the business days; i.e. exclude weekends
How to:
Here is some code to get the first business day after or before the weekend. It is surprisingly simple but thought the code may help save folks some time. Just a note that there is no built-in .Net feature to give you public US or other holiday calendar dates, you need to build your own using a table to keep track of public holidays in most situations. Simple enough to do, extend the methods below to query a database or xml or JSON, etc, file with your company or country holiday calendar.
public static class DayOfWeekUtility
{
public static DateTime GetFirstBusinessDayAfter(DateTime baseDate)
{
var businessDate = baseDate;
var dayOfWeek = businessDate.DayOfWeek;
if (dayOfWeek == DayOfWeek.Saturday || dayOfWeek == DayOfWeek.Sunday)
{
if (dayOfWeek == DayOfWeek.Saturday)
businessDate = businessDate.AddDays(2);
if (dayOfWeek == DayOfWeek.Sunday)
businessDate = businessDate.AddDays(1);
}
return businessDate;
}
public static DateTime GetFirstBusinessDayBefore(DateTime baseDate)
{
var businessDate = baseDate;
var dayOfWeek = businessDate.DayOfWeek;
if (dayOfWeek == DayOfWeek.Saturday || dayOfWeek == DayOfWeek.Sunday)
{
if (dayOfWeek == DayOfWeek.Saturday)
businessDate = businessDate.AddDays(-1);
if (dayOfWeek == DayOfWeek.Sunday)
businessDate = businessDate.AddDays(-2);
}
return businessDate;
}
}