首页 > 解决方案 > 如果我为 Date.prototype.getTime() 提供参数怎么办?

问题描述

我通过两种方式创建日期:

我在阅读 MDN 之前就这样做了,Date.prototype.getTime()没有参数。这意味着第二种方式是错误的。尽管如此,它以正确的方式给出了相同的日期值(new Date('*some date*').getTime();),但毫秒数不同,我不明白为什么。

有人可以解释一下吗?

(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

})();

标签: javascriptdateutcgettime

解决方案


它以正确的方式给出相同的日期值

不,它没有 - 只是当你与你一起调试时,console.log(Date(date1).toString());你又掉进了另一个陷阱:new在调用Date. 正如MDN 所说

调用Date()函数(不带new关键字)返回当前日期和时间的字符串表示,完全一样new Date().toString()。函数调用中给出的任何参数Date()(没有new关键字)都将被忽略;无论是使用无效的日期字符串调用它——还是使用任意对象或其他原语作为参数调用它——它总是返回当前日期和时间的字符串表示。

因此,如果你也解决了这个问题,你会意识到你得到的两个不同的毫秒值getTime()实际上代表了两个不同的日期:

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`);


推荐阅读