10

I'm trying to loop through EACH DAYof the WEEK between 2 time periods

  DateTime start = new DateTime(2010, 1, 1);
  DateTime end = new DateTime(2011, 12, 12);

I have managed to get the number of days between these dates using the following code

     TimeSpan range = (end - start);

turn out to be 710.

I am now looking to get for each month the DAYs OF THE WEEK,

FOR instance

Jan 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 171 18 19 20 . . .

with the matching

M T W T F S S M T W T F S S M

I understand c# has a property from DateTime class DayOfWeek which gets the day of the week my problem is constructing a loop to do the above?

anyone?

Calibre2010
  • 3,729
  • 9
  • 25
  • 35
  • 1
    Fast way : http://stackoverflow.com/questions/22258070/datetime-dayofweek-micro-optimization – rpax Mar 09 '14 at 13:04

3 Answers3

21

This will loop through all days from the start date to the end date and get the day of week for each.

DateTime startDate = new DateTime(2010, 1, 1);
DateTime endDate = new DateTime(2011, 12, 12);
for (DateTime date = startDate; date <= endDate; date = date.AddDays(1))
{
    DayOfWeek dw = date.DayOfWeek;
    // ...
}

Unless you're really worried about optimization, I wouldn't spring for anything more complicated.

Aaronaught
  • 120,909
  • 25
  • 266
  • 342
  • for (DateTime date = startDate; date <= endDate; date = date.AddDays(1)) { DayOfWeek dw = date.DayOfWeek; // ... } Thanks very Much, Appreciate it :) – Calibre2010 Apr 21 '10 at 14:42
  • If he's really worried about optimization, he can take a look to http://stackoverflow.com/questions/22258070/datetime-dayofweek-micro-optimization . It's funny – rpax Mar 09 '14 at 13:04
  • Hardly seems worth the trouble to substitute a custom (and probably buggy) function for a library method, especially when it doesn't even change the Big-O complexity. And again, if you're operating under *really* tight performance constraints - you could simply avoid the whole calculation altogether and just loop from 1 to 7 with a simple test condition. I prefer the method above because it's simple to read/understand, which 9 times out of 10 should be your goal. – Aaronaught Mar 09 '14 at 15:39
3

I like the following:

static IEnumerable Days(DateTime start, DateTime end)
{
    while (start < end)
    {
        string day = start.ToString("ddd");

        start = start.AddDays(1);

        yield return day;
    }
}

How to use it:

foreach(string s in Days(new DateTime(2010, 1, 1), new DateTime(2010, 2, 1)))
{
    Console.WriteLine(s);
}

You can modify it to return various types, of course.

Krisc
  • 1,357
  • 2
  • 14
  • 22
3

Using LINQ:

DateTime start = new DateTime(2010, 1, 1);
DateTime end = new DateTime(2011, 12, 12);
int days = (end  - start).Days;

Enumerable
    .Range(0, days)
    .Select(x => start.AddDays(x))
    .ToList()
    .ForEach(d =>
    {
        DayOfWeek dayOfWeek = d.DayOfWeek;
        // do what you want
    });
Oleks
  • 31,955
  • 11
  • 77
  • 132