Date.now()

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

Date.now() 静态方法返回自 epoch(定义为 1970 年 1 月 1 日午夜,UTC)以来经过的毫秒数。

试一试

// This example takes 2 seconds to run
const start = Date.now();

console.log("starting timer...");
// Expected output: "starting timer..."

setTimeout(() => {
  const ms = Date.now() - start;

  console.log(`seconds elapsed = ${Math.floor(ms / 1000)}`);
  // Expected output: "seconds elapsed = 2"
}, 2000);

语法

js
Date.now()

参数

无。

返回值

一个数字,表示当前时间的 时间戳(以毫秒为单位)。

描述

时间精度降低

为了防止计时攻击和 指纹识别Date.now() 的精度可能会根据浏览器设置进行舍入。在 Firefox 中,privacy.reduceTimerPrecision 首选项默认启用,默认为 2ms。您也可以启用 privacy.resistFingerprinting,在这种情况下,精度将是 100ms 或 privacy.resistFingerprinting.reduceTimerPrecision.microseconds 的值(以较大者为准)。

例如,在时间精度降低的情况下,Date.now() 的结果将始终是 2 的倍数,或者在启用了 privacy.resistFingerprinting 的情况下是 100(或 privacy.resistFingerprinting.reduceTimerPrecision.microseconds)的倍数。

js
// reduced time precision (2ms) in Firefox 60
Date.now();
// Might be:
// 1519211809934
// 1519211810362
// 1519211811670
// …

// reduced time precision with `privacy.resistFingerprinting` enabled
Date.now();
// Might be:
// 1519129853500
// 1519129858900
// 1519129864400
// …

示例

测量经过的时间

您可以使用 Date.now() 获取当前时间的毫秒数,然后减去之前的时间,以确定两次调用之间经过了多长时间。

js
const start = Date.now();
doSomeLongRunningProcess();
console.log(`Time elapsed: ${Date.now() - start} ms`);

对于更复杂的场景,您可能希望改用 Performance API

规范

规范
ECMAScript® 2026 语言规范
# sec-date.now

浏览器兼容性

另见