2011-03-23 28 views
0

我需要生產日期範圍的列表,從而使輸出最終會:操縱日期時間值無法正常工作使用的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! 

我的邏輯有什麼明顯的錯誤,我沒有看到?

回答

1

您不斷乘以-1的noOfYears變量,因此它始終在-1和1之間切換。請嘗試使用noOfYears * -1(不帶等號)。

+0

好的。我沒有注意到這一點。 – FreeAsInBeer 2011-03-23 13:01:59

+0

斑點!謝謝 – DaveDev 2011-03-23 14:02:06

1
currentDate.AddYears(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)); 
}