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

AddWorkDays (fixed version)

Fixed version of AddWorkDays

Source

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

            default:
                return true;
        }
    }

    public static bool IsWeekend(this DayOfWeek dow)
    {
        return !dow.IsWeekday();
    }
        
    public static DateTime AddWorkdays(this DateTime startDate, int days)
    {
        // start from a weekday        
        while (startDate.DayOfWeek.IsWeekend())
            startDate = startDate.AddDays(1.0);

        for (int i = 0; i < days; ++i)
        {
            startDate = startDate.AddDays(1.0);

            while (startDate.DayOfWeek.IsWeekend()) 
                startDate = startDate.AddDays(1.0);
        }
        return startDate;
    }
}

Example

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

//Fixed version

Author: Kevin Cook

Submitted on: 20 mei 2014

Language: C#

Type: AddWorkDays

Views: 4890