【问题标题】:What if I give parameter for Date.prototype.getTime()?如果我为 Date.prototype.getTime() 提供参数怎么办?
【发布时间】:2021-12-06 17:55:48
【问题描述】:

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

  • new Date('某个日期').getTime();
  • new Date().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

})();

【问题讨论】:

    标签: javascript date utc gettime


    【解决方案1】:

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

    不,它没有 - 只是当您使用 console.log(Date(date1).toString()); 进行调试时,您陷入了另一个陷阱:在调用 Date 时缺少 new 运算符。作为MDN puts it

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-25
      • 2010-10-15
      • 1970-01-01
      • 2022-07-25
      • 1970-01-01
      • 2023-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多