我需要生产日期范围的列表,从而使输出最终会:操纵日期时间值无法正常工作使用的DateTime作为循环索引时如预期
0 – 28/02/2009 to 31/02/2010
1 – 31/03/2009 to 31/03/2010
2 – 30/04/2009 to 30/04/2010
3 – 31/05/2009 to 31/05/2010
4 – 30/06/2009 to 30/06/2010
5 – 31/07/2009 to 31/07/2010
6 – 31/08/2009 to 31/08/2010
7 – 30/09/2009 to 30/09/2010
8 – 31/10/2009 to 31/10/2010
9 – 30/11/2009 to 30/11/2010
10 – 31/12/2009 to 31/12/2010
11 – 31/01/2010 to 31/01/2011
12 – 28/02/2010 to 28/02/2011
所以我创建了一个for
环路先从latestDate - 周为第一要素的结束日期和结束日期的开始日期 - 1年,然后到1个月每次迭代incremement循环的指数,如下:
DateTime latestDate = new DateTime(2011, 2, 28);
int noOfYears = 1; // could vary
int shift = 1; // could vary
Dictionary<DateTime, DateTime> dateRanges = new Dictionary<DateTime, DateTime>();
for (var currentDate = latestDate.AddYears(noOfYears *= -1);
currentDate <= latestDate; currentDate.AddMonths(shift))
{
dateRanges.Add(currentDate.AddYears(noOfYears *= -1), currentDate);
}
我我认为这会非常有效,但由于某种原因,我不理解第二currentDate.AddYears(noOfYears *= -1)
似乎并不奏效,因为在字典中的第一项是:
28/02/2011 , 28/02/2010 // the first date here should be minus 2 years!?
在哪里我本来期望
28/02/2009 , 28/02/2010 // the first in the list above
当第二次第二项的循环迭代字典是:
28/02/2009 , 28/02/2010 // this should be first in the dictionary!
我的逻辑有什么明显的错误,我没有看到?
好的。我没有注意到这一点。 – FreeAsInBeer 2011-03-23 13:01:59
斑点!谢谢 – DaveDev 2011-03-23 14:02:06