Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DateTime in a For loop, incrementing date Isn't working

I have this loop, its purpose is to loop through a range of dates and perform some logic to automate adding entries into the database. The issue is that the incrementing portion, date.AddDays(1.0) isn't working, and is always the same result, causing an infinite loop. Any insight?

for (DateTime date = DateTime.Now; futureDate.CompareTo(date) > 0; date.AddDays(1.0)) {     // logic here } 
like image 688
Grahame A Avatar asked Aug 11 '10 17:08

Grahame A


1 Answers

DateTime.AddDays returns a new instance without modifying date. At the moment you're throwing away this new instance. Instead, you need to do:

for (DateTime date = DateTime.Now; futureDate.CompareTo(date) > 0; date = date.AddDays(1.0)) {     // logic here } 

Also, I'm not sure why you're calling CompareTo when you could use the < operator. I can't tell whether CompareTo(date) > 0 is correct without thinking about it for a moment, whereas the intent of the < operator is obvious:

for (DateTime date = DateTime.Now; date < futureDate; date = date.AddDays(1.0)) {     // logic here } 
like image 147
Tim Robinson Avatar answered Sep 24 '22 04:09

Tim Robinson