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

瀏覽器相容性

另見