Manipulating DateTime values not working as expected when using DateTime as loop index
I need to produce a list of date ranges, so that the output will eventually be:
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
So I've created a for
loop to start with the latestDate - 1 year as the first element's end date, and a start date of the end date - 1 year, and then to incremement the loop's index by 1 month each iteration, as follows:
DateTime latestDate = new DateTime(2011, 2, 28);
i开发者_运维技巧nt 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);
}
I thought this would work smashingly but for some reason that I don't understand currentDate.AddYears(noOfYears *= -1)
doesn't seem to be working, because the first entry in the dictionary is:
28/02/2011 , 28/02/2010 // the first date here should be minus 2 years!?
Where I would have expected
28/02/2009 , 28/02/2010 // the first in the list above
When the loop iterates for the second time the second entry to the dictionary is:
28/02/2009 , 28/02/2010 // this should be first in the dictionary!
Is there something obviously wrong with my logic that I'm not seeing?
You're constantly multiplying the noOfYears
variable by -1, so it keeps switching between -1 and 1. Try using noOfYears * -1
instead (without the equals-sign).
currentDate.AddYears(noOfYears *= -1)
will flip the value of noOfYears back and forth from 1 to -1, to 1, to -1, ... I'm not sure why you need to do this.
Also you are not changing the value of currentDate. Try this:
// 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));
}
精彩评论