Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate between two dates in C#

Tags:

c#

datetime

I have two dates:

DateTime fromDate = new DateTime(2013,7,27,12,0,0);
DateTime toDate = new DateTime(2013,7,30,12,0,0);

I want to iterate from fromDate to toDate by incrementing fromDate with a single day and the loop should break when fromDate becomes equal to or greater than the toDate. I have tried this:

while(fromDate < toDate)
{
fromDate.AddDays(1);
}

But this is an infinite loop and won't stop. How can I do this ?

like image 534
Ali Shahzad Avatar asked Jul 27 '13 12:07

Ali Shahzad


1 Answers

Untested but should work:

for(DateTime date = fromDate; date < toDate; date = date.AddDays(1)) {
}

Modify the comparison to <= if you want to include toDate as well.

like image 182
tia Avatar answered Oct 26 '22 17:10

tia