Loop through a date range with JavaScript
Solution 1
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.
Solution 2
Based on Tom Gullen´s answer.
var start = new Date("02/05/2013");
var end = new Date("02/10/2013");
var loop = new Date(start);
while(loop <= end){
alert(loop);
var newDate = loop.setDate(loop.getDate() + 1);
loop = new Date(newDate);
}
Solution 3
I think I found an even simpler answer, if you allow yourself to use Moment.js:
// cycle through last five days, today included
// you could also cycle through any dates you want, mostly for
// making this snippet not time aware
const currentMoment = moment().subtract(4, 'days');
const endMoment = moment().add(1, 'days');
while (currentMoment.isBefore(endMoment, 'day')) {
console.log(`Loop at ${currentMoment.format('YYYY-MM-DD')}`);
currentMoment.add(1, 'days');
}
<script src="https://cdn.jsdelivr.net/npm/moment@2/moment.min.js"></script>
Solution 4
If startDate and endDate are indeed date objects you could convert them to number of milliseconds since midnight Jan 1, 1970, like this:
var startTime = startDate.getTime(), endTime = endDate.getTime();
Then you could loop from one to another incrementing loopTime by 86400000 (1000*60*60*24) - number of milliseconds in one day:
for(loopTime = startTime; loopTime < endTime; loopTime += 86400000)
{
var loopDay=new Date(loopTime)
//use loopDay as you wish
}
Solution 5
Here simple working code, worked for me
var from = new Date(2012,0,1);
var to = new Date(2012,1,20);
// loop for every day
for (var day = from; day <= to; day.setDate(day.getDate() + 1)) {
// your day is here
}
Related videos on Youtube
Comments
-
Tom Gullen almost 2 years
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!
-
Tom Gullen over 13 years+1, gave me enough to work on, ive included the working solution in my question
-
Tom Gullen over 13 yearsOne comment for this is that a less than comparison is prefered over !=, as when loop over multiple months for some reason the != comparison never fires.
-
user1899201 over 12 yearsthis does not work when looping past a daylight savings time change (in areas where that is an issue). Good solution otherwise.
-
Jeremy J Starcher over 11 yearsYou can't assume there are
86400000
seconds in a day. This loop is fragile to daylight savings changes and other edge conditions. -
Owen about 11 yearsSo much more readable than all the other answers. Adding 86400000 miliseconds each loop is not very readable.
-
Ali Guliyev almost 11 yearsBesides DST, another edge condition is "Leap Second". A one second difference does matter - Dates converted to milliseconds correspond to first second of a given day. One second error and you land on previous day.
-
Ali Guliyev almost 11 yearsBesides DST, another edge condition is "Leap Second". A one second difference does matter - Dates converted to milliseconds correspond to first second of a given day. One second error and you land on previous day.
-
Rafael Fontes over 10 yearsBe careful with daylight saving times. d.getDate() + 1 when d.getDate() = GMT N and d.getDate() + 1 = GMT N - 1 d.getDate() + 1 returns the same day of month twice.
-
tatlar over 9 yearsWhy do
Date.now()
when definingnow
?new Date()
returns the current date as an object by default. CallingDate
without thenew
constructor just gives you a Date string which you then convert to a Date object anyway? -
Tk421 over 7 yearsFor me
new Date(2012, 0, 1);
was picking up the incorrect day (one day before),new Date(Date.UTC(2012, 0, 1))
worked fine. -
Erik Kubica almost 7 yearsI have tried multiple solutions on the internet. Weird is that it skips sometimes some days. Like 1.12, 2.12, 3.12, 5.12... (notice that 4.12 is skipped) i have no idea why it happens... Anyone got this problem and found a solution?
-
Erik Kubica almost 7 yearsIf i generate full year from 1.1 to 31.12 it works fine, if i generate custom date range, it's skipping same dates
-
Dmitri Pisarev over 5 years@DevAllanPer nothing,
Date
is a global object developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
Mirek Rusin about 4 years``` d = new Date('2019-03-31') d.setDate(d.getDate() + 1) d.toISOString().slice(0, 10) // 2019-03-31 ``` ^^ fail.
-
loop over 2 years@MirekRusin That's because toISOString disregards the local time zone setting and prints the date as it would be on the UTC time zone. See stackoverflow.com/a/17415677/3070613
-
N. Antonov over 2 yearsCan anyone show an example of how this one breaks with daylight saving time?
-
Jan about 2 years
loop = new Date(newDate);
is not needed. You already set loop withloop.setDate(loop.getDate() + 1);