大网数据广告活动
Web 标准与前端开发

Date.now()

· 52CE 我爱测

**`Date.now()`** 方法返回自 1970 年 1 月 1 日 00:00:00 (UTC) 到当前时间的毫秒数。

Date.now() 方法返回自 1970 年 1 月 1 日 00:00:00 (UTC) 到当前时间的毫秒数。

JavaScript Demo: Date.now()

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

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

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

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

语法

var timeInMs = Date.now();

返回值

一个 Number,表示自 UNIX 纪元开始(1970 年 1 月 1 日 00:00:00 (UTC))到当前时间的毫秒数。

描述

因为 now() 是 Date 的一个静态函数,所以必须以 Date.now() 的形式来使用。

时间精度被降低

为了提供针对定时攻击和指纹追踪的保护,Date.now() 的精度可能会根据浏览器的高级设置项目而被取整。 在 Firefox 中,默认启用 privacy.reduceTimerPrecision 设置项,在 Firefox 59 中,默认被取整至 20 微秒;在 Firefox 60 中,则被取整至 2 毫秒。

// reduced time precision (2ms) in Firefox 60
Date.now();
// 1519211809934
// 1519211810362
// 1519211811670
// ...

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

在 Firefox 中,还可以通过启用 privacy.resistFingerprinting 来进一步降低精度。启用后,精度将为 100 毫秒或者 privacy.resistFingerprinting.reduceTimerPrecision.microseconds 的值,取决于这两个值中哪一个更大,也就是,精度更低一些。

规范

浏览器兼容性

参见

  • Performance.now() — 提供了精确到亚毫秒(sub-millisecond)的时间戳,用于衡量网页性能。
  • console.time / console.timeEnd

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。