Aks Aks - 1 month ago 68
C# Question

c# DateTime to Add/Subtract Working Days

I have a scenario where given a date(

DateTime
),that date plus/minus
x
days(achieved with
DateTime.AddDays
) must add or subtract
x
working days, i.e., skip weekends and holidays. How can I get it to do this? Should I implement my own version and attach it to a calendar or something?

Answer

I would suggest that you have to implement it by your own, and would do it inside an extension method like this:


public static class DateTimeExtensions
{
    public static DateTime AddWorkdays(this DateTime originalDate, int workDays)
    {
        DateTime tmpDate = originalDate;
        while (workDays > 0)
        {
            tmpDate = tmpDate.AddDays(1);
            if (tmpDate.DayOfWeek < DayOfWeek.Saturday && 
                tmpDate.DayOfWeek > DayOfWeek.Sunday &&
                !tmpDate.IsHoliday())
                workDays--;
        }
        return tmpDate;
    }

    public static bool IsHoliday(this DateTime originalDate)
    {
        // INSERT YOUR HOlIDAY-CODE HERE!
        return false;
    }
}