Possible Duplicate:
How do I loop through a date range?
Is there a way to make a foreach loop for each day in a specific month?
thinking of something like
foreach (DateTime date in DateTime.DaysInMonth(2012, 1))
{
}
Possible Duplicate:
How do I loop through a date range?
Is there a way to make a foreach loop for each day in a specific month?
thinking of something like
foreach (DateTime date in DateTime.DaysInMonth(2012, 1))
{
}
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.
Try using a for loop instead.
for (int i = 1; i <= DateTime.DaysInMonth(year, month); i++)
{
DateTime dt = new DateTime(year, month, i);
}
You can use Range:
Enumerable
.Range(1, DateTime.DayInMonth(2012, 1)
.Select(i => new DateTime(2012, 1, i)))
.ToList() // ForEach is not a Linq to Sql method (thanks @Markus Jarderot)
.ForEach(day => Console.Write(day));
You can do it with a simple loop:
DateTime first = new DateTime(2012, 1, 1);
for (DateTime current = first ; current.Month == first.Month ; current = current.AddDays(1)) {
}