Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
184
rated 0 times [  190] [ 6]  / answers: 1 / hits: 199548  / 14 Years ago, fri, december 3, 2010, 12:00:00

Given two Date() objects, where one is less than the other, how do I loop every day between the dates?



for(loopDate = startDate; loopDate < endDate; loopDate += 1)
{

}


Would this sort of loop work? But how can I add one day to the loop counter?



Thanks!


More From » loops

 Answers
24

Here's a way to do it by making use of the way adding one day causes the date to roll over to the next month if necessary, and without messing around with milliseconds. Daylight savings aren't an issue either.



var now = new Date();
var daysOfYear = [];
for (var d = new Date(2012, 0, 1); d <= now; d.setDate(d.getDate() + 1)) {
daysOfYear.push(new Date(d));
}


Note that if you want to store the date, you'll need to make a new one (as above with new Date(d)), or else you'll end up with every stored date being the final value of d in the loop.


[#94748] Wednesday, December 1, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zachariaho

Total Points: 34
Total Questions: 87
Total Answers: 100

Location: England
Member since Tue, Sep 8, 2020
4 Years ago
zachariaho questions
Tue, Jul 27, 21, 00:00, 3 Years ago
Mon, May 31, 21, 00:00, 3 Years ago
Fri, Apr 30, 21, 00:00, 3 Years ago
;