从一个给定的日期起,可以轻松地循环几个月和几年 [英] easy way to loop over months and years from a given date

查看:183
本文介绍了从一个给定的日期起,可以轻松地循环几个月和几年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图写这个循环,而且它越来越复杂。基本上我希望每个月都有一个给定的日期和循环,直到我到达本月。所以如果开始日期是11/1/2011,那么我想循环

I have been trying to write this loop and it just keeps getting more complicated. Basically I want to take a given date and loop through every month until I reach the current month. So if the start date is 11/1/2011 then I want to loop through

11/2011,12/2011,1/2012,2/2012等。

11/2011, 12/2011, 1/2012, 2/2012, etc.

这是我开始的,但这不行。一旦我打了一个新的一年,我需要内循环重新开始,1不是startdate.Month。有没有更好的方法来循环几个月和几年?
感谢

Here is what I started with but this does not work. Once I hit a new year I need the inner loop to start over with 1 not startdate.Month. Is there a better way in general to loop through months and years? Thanks

        for (var y = startdate.Year; y <= DateTime.Now.Year; y++)
        {
            for (var m = startdate.Month; m <= 12; m++)
            {
                  //do something with m and y
            }
        }


推荐答案

Date target = new Date(2011, 4, 1);
while (target < Date.Today) {
  // do something with target.Month and target.Year
  target = target.AddMonths(1);
}

这篇关于从一个给定的日期起,可以轻松地循环几个月和几年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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