C# 一个月中的每一天
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9097027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
foreach day in month
提问by Michael Tot Korsgaard
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?
有没有办法为特定月份的每一天制作一个 foreach 循环?
thinking of something like
想着类似的事情
foreach (DateTime date in DateTime.DaysInMonth(2012, 1))
{
}
采纳答案by Jon Skeet
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 forloop or something similar if you're doing this a lot. It makes your code say justwhat you want to achieve, rather than the mechanics for how you're doing it.
对于您只做一次的事情来说,这可能是矫枉过正,但for如果您经常这样做,它比使用循环或类似的东西要好得多。它使您的代码只说明您想要实现的目标,而不是说明您如何实现的机制。
回答by Brandon
Try using a for loop instead.
尝试改用 for 循环。
for (int i = 1; i <= DateTime.DaysInMonth(year, month); i++)
{
DateTime dt = new DateTime(year, month, i);
}
回答by dasblinkenlight
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)) {
}
回答by Joe
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));
回答by Huusom
It is fairly easy to generate an enumeration of days. Here is one way to do it
生成天数枚举相当容易。这是一种方法
Enumerable.Range(1, DateTime.DaysInMonth(year, month)).Select(day =>
new DateTime(year, month, day))

