0

Javascript getTime() returns different time than time object itself.

function doTime(){
  var data = [];
  var newDate = new Date('2020-01-01');

  for (var i = 0; i < 10; i++) {
    newDate.setTime(newDate.getTime() + (1000 * 60 * 60));
    console.log(newDate);                //<<----these times are not the same for some reason, why?
    data.push({'date': newDate});        //<<----these times are not the same for some reason, why?
    }
  console.log(data);
  }

And the output!!

Wed Jan 01 2020 03:00:00 GMT+0200 (Eastern European Standard Time)
Wed Jan 01 2020 04:00:00 GMT+0200 (Eastern European Standard Time)
Wed Jan 01 2020 05:00:00 GMT+0200 (Eastern European Standard Time)
Wed Jan 01 2020 06:00:00 GMT+0200 (Eastern European Standard Time)
Wed Jan 01 2020 07:00:00 GMT+0200 (Eastern European Standard Time)
................

(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {date: Wed Jan 01 2020 12:00:00 GMT+0200 (Eastern European Standard Time)}
1: {date: Wed Jan 01 2020 12:00:00 GMT+0200 (Eastern European Standard Time)}
2: {date: Wed Jan 01 2020 12:00:00 GMT+0200 (Eastern European Standard Time)}
3: {date: Wed Jan 01 2020 12:00:00 GMT+0200 (Eastern European Standard Time)}
4: {date: Wed Jan 01 2020 12:00:00 GMT+0200 (Eastern European Standard Time)}
................

btw I already solved this problem with a slightly different code, but can someone please explain why is this happening?

Harijs Krūtainis
  • 1,261
  • 14
  • 13
  • 1
    The array has 5 references to the same Date object: `data[0] === data[1] === data[2] ...`. Use `data.push({'date': new Date(newDate)})`. – RobG Sep 29 '20 at 00:25

1 Answers1

6

You aren't creating a new reference in your loop, so you are mutating the same newDate each time. You are also calling console.log so at that time, it's converted to its console format.

halfer
  • 19,824
  • 17
  • 99
  • 186
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445