3

In my app (c#) I need to add n days to today's date. I know that I can use DateTime.AddDays(n) method, and this method works fine. But in my situation I want to add only working days (or only "Mondays" and "Fridays" or any other sets).

Maybe exist any default methods to calculate such type of logic.

Test data:

Date: Today (24-jun-2014).
Days to add: 10
Days type: Business days (Mn-Fr)
Answer: 8-july-2014

jimpanzer
  • 3,470
  • 4
  • 44
  • 84
  • I would create an enum of days then as you iterate over the days that you are adding check it against your enum – DotNetRussell Jun 24 '14 at 14:01
  • There's no build-in method. There are several answers on SO to calculate business days. – D Stanley Jun 24 '14 at 14:05
  • @DStanley, thanks for you comment, but what about custom set of days (Fr-Sun)? Maybe question not duplicated? – jimpanzer Jun 24 '14 at 14:10
  • You question asked if there are any "default methods" - the answer is no - there may be third-party libraries, or you can roll your own which has several answers on SO. – D Stanley Jun 24 '14 at 15:38

2 Answers2

3

You could use LINQ:

DayOfWeek[] weekEnd = { DayOfWeek.Saturday, DayOfWeek.Sunday };
DateTime end = Enumerable.Range(0, int.MaxValue)
            .Select(i => DateTime.Today.AddDays(i))
            .Where(d => !weekEnd.Contains(d.DayOfWeek))
            .Take(10)
            .Last();

However, it returns 07/07, i assume because it includes today. I don't know if it is desired. If you don't want to include today change Range(0, int.MaxValue) to Range(1, int.MaxValue).

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

I would do it this way:

    public static DateTime AddBusinessDays(this DateTime source, int daysToAdd, params DayOfWeek[] workdays)
    {
        if (daysToAdd <= 0)
            return source;
        var current = source;

        while (daysToAdd > 0)
        {
            current = current.AddDays(1);

            if (workdays.Contains(current.DayOfWeek))
                daysToAdd--;
        }

        return current;
    }
Dbl
  • 5,634
  • 3
  • 41
  • 66