AddBusinessDays Function - C#

Overview

This function reproduces the Excel WORKDAY() function, which adds a number of business days to a given date.

For a T-SQL (SQL Server) version of this function, see WorkDay Function - SQL Server.

Code

public static DateTime AddBusinessDays(this DateTime inputDate, int offset)
{
    var wholeWeeks = (double)(Math.Truncate(Math.Abs(offset) / (decimal)5) * Math.Sign(offset));
            
    var result = inputDate.AddDays(wholeWeeks * 7);
            
    var extraDays = offset % 5;
            
    var result2 = result.AddDays(extraDays);

    if (
        ((int)result2.DayOfWeek < (int)result.DayOfWeek && offset > 0) ||
        ((int)result2.DayOfWeek > (int)result.DayOfWeek && offset < 0) ||
        (result2.DayOfWeek == DayOfWeek.Sunday) ||
        (result2.DayOfWeek == DayOfWeek.Saturday)
        )
    {
        wholeWeeks += Math.Sign(offset);
        extraDays -= 5 * Math.Sign(offset);
    }

    var result3 = inputDate.AddDays(wholeWeeks * 7 + extraDays);

    return result3;
}