using DateTime in a for/next loop

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Does anyone know why you cannot add days/months/years to a DateTime variable in a for next loop?

ArrayList ary = new ArrayList();
for (DateTime sd = start_date;sd <= end_date;sd.AddDays(1))
{
string moYear = sd.Month.ToString().PadLeft(2,'0') + sd.Year.ToString();
if (!ary.Contains(moYear))
ary.Add(moYear);
}
 
Bill Szerdy said:
Does anyone know why you cannot add days/months/years to a DateTime
variable in a for next loop?

You can. However, calling AddDays doesn't change the existing DateTime,
it returns a new one.
ArrayList ary = new ArrayList();
for (DateTime sd = start_date;sd <= end_date;sd.AddDays(1))

Change the last bit to sd = sd.AddDays(1);
 
Back
Top