Iterate between two dates in C #

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 fromDate to toDate, incrementing fromDate from one day, and the loop should break when fromDate becomes equal to or greater than toDate. I tried this:

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

But this is an endless cycle and will not stop. How can i do this?

+4
source share
2 answers

DateTime.AddDays does add the specified number of days to the date, but the total date is returned as a new DateTime value; The original DateTime value does not change.

Therefore, make sure that you return the result of your operation to a variable that you check in your loop state:

 while (fromDate < toDate) { fromDate = fromDate.AddDays(1); } 
+4
source

Unconfirmed, but should work:

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

Change the comparison to <= if you want to include toDate .

+6
source

Source: https://habr.com/ru/post/1493804/


All Articles