foreach day in month [duplicate]

You can write a helper method pretty easily:

public static IEnumerable<DateTime> AllDatesInMonth(int year, int month)
{
    int days = DateTime.DaysInMonth(year, month);
    for (int day = 1; day <= days; day++)
    {
         yield return new DateTime(year, month, day);
    }
}

Then call it with:

foreach (DateTime date in AllDatesInMonth(2012, 1))

This is probably overkill for something you’re only doing once, but it’s much nicer than using a for loop or something similar if you’re doing this a lot. It makes your code say just what you want to achieve, rather than the mechanics for how you’re doing it.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)