每个月的前一天
可能重复:
如何遍历日期范围?
有没有办法在特定月份的每一天制作一个foreach循环?
想着类似的东西
foreach (DateTime date in DateTime.DaysInMonth(2012, 1)) { }
您可以非常轻松地编写辅助方法:
public static IEnumerable 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); } }
然后用:
foreach (DateTime date in AllDatesInMonth(2012, 1))
对于你只做过一次的事情来说,这可能有点过头了,但是如果你这么做的话,它比使用for
循环或类似东西要好得多。 它使你的代码说出你想要实现的目标,而不是你如何做到这一点的机制。
请尝试使用for循环。
for (int i = 1; i <= DateTime.DaysInMonth(year, month); i++) { DateTime dt = new DateTime(year, month, i); }
你可以使用范围:
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));
你可以用一个简单的循环来做到这一点:
DateTime first = new DateTime(2012, 1, 1); for (DateTime current = first ; current.Month == first.Month ; current = current.AddDays(1)) { }
生成枚举天很容易。 这是一种方法
Enumerable.Range(1, DateTime.DaysInMonth(year, month)).Select(day => new DateTime(year, month, day))