Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

AddBusinessDays Function - C#

RSS
Modified on Mon, Jul 27, 2020, 1:18 PM by Administrator Categorized as ·Net Framework

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

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.