javascript - 如果我为 Date.prototype.getTime() 提供参数怎么办?
问题描述
我通过两种方式创建日期:
- 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
})();
解决方案
它以正确的方式给出相同的日期值
不,它没有 - 只是当你与你一起调试时,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`);
推荐阅读
- java - 递归不打印错误但卡住了
- sql - 如何从 SQL 查询中检索值并将其存储在 VB.NET 中的变量中?
- azure-cosmosdb - CosmosDB - 存储针对搜索间隔优化的日期时间
- node.js - 如何使用 Lambda 函数了解 RDS 的状态
- python - 获取文件的创建日期,使用该日期创建文件夹并移动文件
- scroll - SwiftUI 无限滚动(上下)
- python - 根据日期计算给定文本文件中每个单词的出现次数
- javascript - 我不知道为什么我不断得到 NaN
- asp.net-mvc - 显示名称的数据注释未以 Razor 形式呈现
- python - 二进制编码(类似于 one-hot 编码),但在单个列和行中允许多个值