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

Page History: AddBusinessDays Function - C#

Compare Page Revisions



« Older Revision - Back to Page History - Current Revision


Page Revision: Mon, Jul 27, 2020, 1:16 PM


Overview

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

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.