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,470
  • 4
  • 44
  • 84
  • 7
    any try from yourside so far? – Neel Jun 28 '14 at 11:44
  • 1
    While doing this *efficiently* would be relatively tricky, if you've only got a few days to add (as in your examples), it should be very simple to just add a day at a time. – Jon Skeet Jun 28 '14 at 11:46
  • Yes, we can use the mechanism, which I provide in question(link "here"), but it takes a lot of conditions. – jimpanzer Jun 28 '14 at 11:46

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,625
  • 3
  • 43
  • 61
  • 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