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 }
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With