0

I create date in two ways:

  • new Date('some date').getTime();
  • new Date().getTime('some date');

I did it before I had read on MDN, that Date.prototype.getTime() doesn't have parameter. It means second way is wrong. Nevertheless, it gives the same date value the right way gives (new Date('*some date*').getTime();) but amount of milliseconds is different and I don't get why.

Could someone explain me?

(function () {

  let dateToCount = "Jan 01, 2022 00:00:00";
  let date1 = new Date(dateToCount).getTime();
  let date2 = new Date().getTime(dateToCount);

  console.log(Date(date1).toString()); // Tue Oct 19 2021 22:41:59 GMT+0300 (Eastern European Summer Time)
  console.log(Date(date2).toString()); // Tue Oct 19 2021 22:41:59 GMT+0300 (Eastern European Summer Time)
  console.log(`date1 = ${date1} ms`); // date1 = 1640988000000 ms
  console.log(`date2 = ${date2} ms`); // date2 = 1634672519002 ms
  console.log(`date1 - date2 = ${+date1 - (+date2)} ms`);  // date1 - date2 = 6315480998 ms

})();
Bergi
  • 630,263
  • 148
  • 957
  • 1,375

1 Answers1

1

it gives the same date value the right way gives

No, it doesn't - it just that when you were debugging with console.log(Date(date1).toString()); you fell in yet another trap: missing the new operator in the call the Date. As MDN puts it:

Calling the Date() function (without the new keyword) returns a string representation of the current date and time, exactly as new Date().toString() does. Any arguments given in a Date() function call (without the new keyword) are ignored; regardless of whether it’s called with an invalid date string — or even called with any arbitrary object or other primitive as an argument — it always returns a string representation of the current date and time.

So if you fix that as well, you'll realise that the two different millisecond values you get back from getTime() actually do represent two different dates:

const dateToCount = "Jan 01, 2022 00:00:00";
const date1 = new Date(dateToCount).getTime();
const date2 = new Date().getTime(dateToCount);

console.log(new Date(date1).toString()); // Sat Jan 01 2022 00:00:00, as expected
console.log(new Date(date2).toString()); // Surprise!
console.log(`date1 = ${date1} ms`);
console.log(`date2 = ${date2} ms`);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375