Loop through a date range with JavaScript
Asked Answered
D

12

191

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!

Dow answered 3/12, 2010 at 11:24 Comment(0)
S
298

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.

Susannahsusanne answered 6/4, 2012 at 7:49 Comment(9)
So much more readable than all the other answers. Adding 86400000 miliseconds each loop is not very readable.Contrastive
Be 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.Capet
Why do Date.now() when defining now? new Date() returns the current date as an object by default. Calling Date without the new constructor just gives you a Date string which you then convert to a Date object anyway?Escort
For me new Date(2012, 0, 1); was picking up the incorrect day (one day before), new Date(Date.UTC(2012, 0, 1)) worked fine.Rectory
I 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?Vicereine
If i generate full year from 1.1 to 31.12 it works fine, if i generate custom date range, it's skipping same datesVicereine
``` d = new Date('2019-03-31') d.setDate(d.getDate() + 1) d.toISOString().slice(0, 10) // 2019-03-31 ``` ^^ fail.Sandrasandro
@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 https://mcmap.net/q/36922/-how-to-iso-8601-format-a-date-with-timezone-offset-in-javascriptSippet
Can anyone show an example of how this one breaks with daylight saving time?Thankyou
C
94

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);
}
Charley answered 1/2, 2013 at 21:51 Comment(2)
@DevAllanPer nothing, Date is a global object developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Interrelated
loop = new Date(newDate); is not needed. You already set loop with loop.setDate(loop.getDate() + 1);Bandicoot
A
16

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>
Arnhem answered 1/4, 2018 at 21:1 Comment(0)
D
14

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
   console.log(day)
}
Deyo answered 7/12, 2017 at 20:32 Comment(0)
L
11

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
}
Lorianne answered 3/12, 2010 at 11:36 Comment(4)
+1, gave me enough to work on, ive included the working solution in my questionDow
this does not work when looping past a daylight savings time change (in areas where that is an issue). Good solution otherwise.Durr
You can't assume there are 86400000 seconds in a day. This loop is fragile to daylight savings changes and other edge conditions.Clotilde
Besides 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.Greensward
J
3
var start = new Date("2014-05-01"); //yyyy-mm-dd
var end = new Date("2014-05-05"); //yyyy-mm-dd

while(start <= end){

    var mm = ((start.getMonth()+1)>=10)?(start.getMonth()+1):'0'+(start.getMonth()+1);
    var dd = ((start.getDate())>=10)? (start.getDate()) : '0' + (start.getDate());
    var yyyy = start.getFullYear();
    var date = dd+"/"+mm+"/"+yyyy; //yyyy-mm-dd

    alert(date); 

    start = new Date(start.setDate(start.getDate() + 1)); //date increase by 1
}
Jessjessa answered 6/11, 2014 at 9:49 Comment(0)
K
3

As a function,

function getDatesFromDateRange(from, to) {
  const dates = [];
  for (let date = from; date <= to; date.setDate(date.getDate() + 1)) {
    const cloned = new Date(date.valueOf());
    dates.push(cloned);
  }
  return dates;
}

const start = new Date(2019, 11, 31);
const end = new Date(2020, 1, 1);

const datesArray = getDatesFromDateRange(start, end);
console.dir(datesArray);
Kayleen answered 22/4, 2022 at 15:32 Comment(0)
M
1

Based on Tabare's Answer, I had to add one more day at the end, since the cycle is cut before

var start = new Date("02/05/2013");
var end = new Date("02/10/2013");
var newend = end.setDate(end.getDate()+1);
var end = new Date(newend);
while(start < end){
   alert(start);           

   var newDate = start.setDate(start.getDate() + 1);
   start = new Date(newDate);
}
Marentic answered 21/2, 2017 at 22:28 Comment(0)
S
1

Didn't want to store the result in an array, so maybe using yield?

/**
 * @param {object} params
 * @param {Date} params.from
 * @param {Date} params.to
 * @param {number | undefined} params.incrementBy
 * @yields {Date}
 */
 function* iterateDate(params) {
    const increaseBy = Math.abs(params.incrementBy ?? 1);
    for(let current = params.from; current.getTime() <= params.to.getTime(); current.setDate(current.getDate() + increaseBy)) {
        yield new Date(current);
    }
}

for (const d of iterateDate({from: new Date(2021,0,1), to: new Date(2021,0,31), incrementBy: 1})) {
    console.log(d.toISOString());
}
Sewole answered 7/5, 2022 at 1:46 Comment(0)
M
0

If you want an efficient way with milliseconds:

var daysOfYear = [];
for (var d = begin; d <= end; d = d + 86400000) {
    daysOfYear.push(new Date(d));
}
Marika answered 25/1, 2019 at 18:20 Comment(0)
B
0

Let us assume you got the start date and end date from the UI and stored it in the scope variable in the controller.

Then declare an array which will get reset on every function call so that on the next call for the function the new data can be stored.

var dayLabel = [];

Remember to use new Date(your starting variable) because if you dont use the new date and directly assign it to variable the setDate function will change the origional variable value in each iteration`

for (var d = new Date($scope.startDate); d <= $scope.endDate; d.setDate(d.getDate() + 1)) {
                dayLabel.push(new Date(d));
            }
Blooded answered 19/7, 2019 at 5:24 Comment(0)
D
-2

Based on Jayarjo's answer:

var loopDate = new Date();
loopDate.setTime(datFrom.valueOf());

while (loopDate.valueOf() < datTo.valueOf() + 86400000) {

    alert(loopDay);

    loopDate.setTime(loopDate.valueOf() + 86400000);
}
Dow answered 3/12, 2010 at 12:1 Comment(2)
One 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.Dow
Besides 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.Greensward

© 2022 - 2024 — McMap. All rights reserved.