2

I am facing a problem, logic written in my program is below

while (lastDate.Month < DateTime.Today.Month - 1)//
  {
    lastDate= lastDate.AddMonths(1);
    list.Add(lastDate);
  }

This code is failing when lastDate month is Dec and i am executing this code in Jan or Feb of new year because 12 would never be greater then 1 0r 2.

I need to write a logic where my loop could traverse through Nov, Dec, Jan , Feb and so on.

I have written below code which is working however i am not getting clue to exit, loop should exit when difference between lastDate and todays date is 2 months.

if (lastDate.Month > DateTime.Today.Month && lastDate.Year < DateTime.Today.Year)
 {
  while (lastDate.Year <= DateTime.Today.Year)
   {
     lastDate= lastDate.AddMonths(1);
     list.Add(lastDate);

   }

}

Please help me in this

4

4 回答 4

1

You will always add 12 months to the list, so you can use a for-loop:

for(var i = 0; i < 12; i++)
{
    lastDate = lastDate.AddMonths(1);
    list.Add(lastDate);
}

As you know how many times you have to add one month, there is no need to have a condition depending on the month and year, but only a counter to execute this code exactly 12 times.

于 2013-04-29T06:34:17.753 回答
0

This may helps:

DateTime lastDate = DateTime.ParseExact("01/12/12", "dd/MM/yy", System.Globalization.CultureInfo.InvariantCulture);

List<DateTime> result = new List<DateTime>();

//iterate until the difference is two months 
while (new DateTime((DateTime.Today - lastDate).Ticks).Month >= 2)
{
    result.Add(lastDate);
    lastDate = lastDate.AddMonths(1);
}

//result: 12/1/2012
//         1/1/2013
//         2/1/2013
//         3/1/2013
于 2013-04-29T06:37:51.467 回答
0

Hopefully this will solve your problem:

DateTime lastDate = new DateTime(2012, 1, 1);
List<DateTime> list = new List<DateTime>();

while (lastDate < (DateTime.Today.AddMonths(-3))) //difference between today and lastDate should be 2 month
{
  lastDate = lastDate.AddMonths(1);
  list.Add(lastDate);
}
于 2013-04-29T06:45:52.503 回答
0

This will add 12 DateTimes from lastDate to your list :)

list.AddRange(Enumerable.Range(0,12).Select(v => lastDate = lastDate.AddMonths(1)));
于 2013-04-29T07:02:10.270 回答