Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through the days of the week inside of C# TimeSpan Class

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?

like image 666
Calibre2010 Avatar asked Apr 21 '10 14:04

Calibre2010


2 Answers

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.

like image 111
Aaronaught Avatar answered Sep 20 '22 17:09

Aaronaught


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.

like image 24
Krisc Avatar answered Sep 19 '22 17:09

Krisc