C# 使用DateTime作为循环索引时,操作DateTime值未按预期工作
我需要生成一个日期范围列表,以便最终输出为:C# 使用DateTime作为循环索引时,操作DateTime值未按预期工作,c#,datetime,for-loop,C#,Datetime,For Loop,我需要生成一个日期范围列表,以便最终输出为: 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 t
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
因此,我为循环创建了一个,以最晚的日期-1年作为第一个元素的结束日期,以结束日期的开始日期-1年作为开始日期,然后在每次迭代中将循环的索引增加1个月,如下所示:
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);
}
在我预料到的地方
28/02/2009 , 28/02/2010 // the first in the list above
循环第二次迭代时,字典的第二个条目为:
28/02/2011 , 28/02/2010 // the first date here should be minus 2 years!?
28/02/2009 , 28/02/2010 // this should be first in the dictionary!
我的逻辑是否有明显的错误,我没有看到?您不断地将noOfYears
变量乘以-1,因此它一直在-1和1之间切换。尝试改用noOfYears*-1
(不带等号)
将noOfYears的值从1来回翻转到-1,从-1翻转到-1。。。
我不知道你为什么要这么做
此外,您没有更改currentDate的值。试试这个:
// note the new start date
DateTime latestDate = new DateTime(2011, 3, 1);
// could vary
int noOfYears = 1;
// could vary
int shift = 1;
var dateRanges = new Dictionary<DateTime, DateTime>();
for (var currentDate = latestDate.AddYears(noOfYears * -1);
currentDate <= latestDate; currentDate = currentDate.AddMonths(shift))
{
dateRanges.Add(currentDate.AddYears(noOfYears *= -1).AddDays(-1),
currentDate.AddDays(-1));
}
//注意新的开始日期
DateTime latestDate=新的日期时间(2011,3,1);
//可能会有所不同
int noOfYears=1;
//可能会有所不同
int-shift=1;
var dateRanges=新字典();
对于(var currentDate=latestDate.AddYears)(noOfYears*-1);
真是个好球,我没注意到。
// note the new start date
DateTime latestDate = new DateTime(2011, 3, 1);
// could vary
int noOfYears = 1;
// could vary
int shift = 1;
var dateRanges = new Dictionary<DateTime, DateTime>();
for (var currentDate = latestDate.AddYears(noOfYears * -1);
currentDate <= latestDate; currentDate = currentDate.AddMonths(shift))
{
dateRanges.Add(currentDate.AddYears(noOfYears *= -1).AddDays(-1),
currentDate.AddDays(-1));
}