Search code examples
javascriptdategettime

Javascript getTime() returns different time than time object itself


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?


Solution

  • 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.