0

I have similar SO question for date calculation for "Bussines days".
And finaly I use mechanism described here.
But this is the particular case.

What about more general approach?
How add specific number (n) of days to current date considering only the days from custom set: Mn-Tu-We or Sa-Su-Me or any other.

Test data 1:
Date: (28-jun-2014).
Days to add: 10
Days type: Mn - Th - Fr
Answer: 21-july-2014

Test data 2:
Date: (28-jun-2014).
Days to add: 5
Days type: Tu - We
Answer: 15-july-2014
Community
  • 1
  • 1
jimpanzer
  • 3,454
  • 4
  • 42
  • 84

1 Answers1

2

From one of the ans specified in link I can make some modification here :-

For test 1:-

DayOfWeek[] daysOfWeek= { DayOfWeek.Monday, DayOfWeek.Thursday, DayOfWeek.Friday};
DateTime end = Enumerable.Range(0, int.MaxValue)
            .Select(i => DateTime.Today.AddDays(i))
            .Where(d => daysOfWeek.Contains(d.DayOfWeek))
            .Take(10)
            .Last();

Answer :- 21-07-2014 00:00:00

For test 2 :-

DayOfWeek[] daysOfWeek= { DayOfWeek.Tuesday, DayOfWeek.Wednesday};
DateTime end = Enumerable.Range(0, int.MaxValue)
            .Select(i => DateTime.Today.AddDays(i))
            .Where(d => daysOfWeek.Contains(d.DayOfWeek))
            .Take(5)
            .Last();

Answer :- 15-07-2014 00:00:00

Neel
  • 11,427
  • 3
  • 42
  • 60
  • 1
    Considering that every time you call `DateTime.Today` it's reading from the system clock, you might consider pulling that out into it's own variable. Then the function will be deterministic - and slightly faster. – Matt Johnson-Pint Jun 30 '14 at 03:37
  • oh yes agree with you @MattJohnson – Neel Jun 30 '14 at 05:08