ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

AddWorkdays

A modification to the AddDay function that adds an integer number of weekdays to a date, starting the count at the first weekday after the current day. This is a typical method for calculating B2B service delivery and billing due dates.

Source

public static class DateTimeExtensions
{
    public static bool IsWeekend(this DayOfWeek d) 
    { 
        return !d.IsWeekday(); 
    }

    public static bool IsWeekday(this DayOfWeek d)
    {
        switch (d)
        {
            case DayOfWeek.Sunday:
            case DayOfWeek.Saturday: return false;

            default: return true;
        }
    }

    public static DateTime AddWorkdays(this DateTime d, int days)
    {
        // start from a weekday
        while (d.DayOfWeek.IsWeekday()) d = d.AddDays(1.0);
        for (int i = 0; i < days; ++i)
        {
            d = d.AddDays(1.0);
            while (d.DayOfWeek.IsWeekday()) d = d.AddDays(1.0);
        }
        return d;
    }
}

Example

DateTime due = DateTime.Today.AddWorkdays(10); // due in 10 workdays

Author: Lee Harding

Submitted on: 5 jun. 2009

Language: C#

Type: System.DateTime

Views: 10163