Date.now() 返回以微秒为单位的值,而不是以毫秒为单位的值

Wat*_* v2 1 javascript browser

Date.now(),根据文档应该返回 Unix 时间戳或纪元时间,即自 1970 年 1 月 1 日以来经过的毫秒数。

根据本网站(或任何其他有效的计算方法),当前的 unix 时间戳约为 1554637184。请注意,该值有 10 位数字。该值实际上以毫秒为单位。

然而,所有三个浏览器(Chrome 73、Firefox 66.0.2 和 Edge 17.17134)返回的值Date.now()都是 1554637694364,观察到它是 13 位数字,因此,我推断它是微秒自1970年1月1日起过去。

这是怎么回事?

我在使用它多年后才意识到这一点,因为刚才我正在调试一些代码,这些代码进行了这样的检查,因此失败了:

let endTime = ...; // a time later than now expressed as a unix timestamp
let now = Date.now();

if (endTime <= now) {
  // And it always came here, and that led me to this discovery
  ...
}
Run Code Online (Sandbox Code Playgroud)

e.d*_*dan 6

当前纪元时间(也称为 unix 时间戳)1554637856是自 1970 年 1 月 1 日以来的秒数而不是毫秒。

Date.now()返回纪元时间(以毫秒为单位),因此您需要秒:

if (endTime <= now / 1000) {
...
Run Code Online (Sandbox Code Playgroud)