Ruth Young
Ruth Young

Reputation: 888

Getting list of dates between two dates not returning correctly JS

I have a start date and an end date, and I want to generate a list of dates between (and including) these two dates. But I don't get why it isn't working...

I pass in a couple of JS date objects, I've shown what they log to the console below

function dateList(dateStart, dateEnd) {
  console.log(dateStart);
  console.log(dateEnd);
  var dates = [];
  for ( i = dateStart; i <= dateEnd; i.setDate(i.getDate() + 1) ){
    dates.push(i);
  }
  return dates
}



Mon May 08 2017 00:00:00 GMT+0100 (BST)
Fri May 12 2017 00:00:00 GMT+0100 (BST)

The array that is returned is

Array[5] 
0: Sat May 13 2017 00:00:00 GMT+0100 (BST)
1: Sat May 13 2017 00:00:00 GMT+0100 (BST)
2: Sat May 13 2017 00:00:00 GMT+0100 (BST)
3: Sat May 13 2017 00:00:00 GMT+0100 (BST)
4: Sat May 13 2017 00:00:00 GMT+0100 (BST)
length: 5
__proto__: Array[0]

...Why???......

Upvotes: 0

Views: 74

Answers (3)

Arg0n
Arg0n

Reputation: 8423

Try to add new Date(i), instead of just i:

function dateList(dateStart, dateEnd) {
  var dates = [];
  for (i = dateStart; i <= dateEnd; i.setDate(i.getDate() + 1)){
    dates.push(new Date(i));
  }
  return dates;
}

console.log(dateList(new Date('2017-05-08'), new Date('2017-05-12')));

Upvotes: 1

Prisoner
Prisoner

Reputation: 50701

Your code i.setDate(i.getDate() + 1) doesn't create a new date - it just updates the same Date object over and over. Then you push that object onto the array, which pushes a reference to that object - not a copy of the object.

A solution would be to create a new Date() inside the loop and setting the value of it, and then pushing this new date onto your array.

Upvotes: 1

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19315

Because the same object is modified all elements referencing the same object

Upvotes: 0

Related Questions