每个月的每一天 [英] foreach day in month

查看:129
本文介绍了每个月的每一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何循环日期范围?


有没有办法在特定月份的每一天做一个foreach循环?



考虑类似于

  foreach(DateTime.DaysInMonth(2012,1)中的日期)
{
}

解决方案

您可以很容易地编写一个帮助方法: pre> public static IEnumerable< DateTime> AllDatesInMonth(int year,int month)
{
int days = DateTime.DaysInMonth(year,month);
for(int day = 1; day <= days; day ++)
{
yield new DateTime(year,month,day);


$ / code>

然后调用它:

  foreach(在AllDatesInMonth(2012,1)中的DateTime日期)

这可能是一次只做一次的东西,但它比用于要好得多。循环或类似的东西,如果你这样做了很多。它使你的代码只是你想要达到什么目的,而不是你如何做的机制。


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.

这篇关于每个月的每一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆