From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../reference/global_objects/date/now/index.html | 101 +++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 files/zh-cn/web/javascript/reference/global_objects/date/now/index.html (limited to 'files/zh-cn/web/javascript/reference/global_objects/date/now') diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/now/index.html b/files/zh-cn/web/javascript/reference/global_objects/date/now/index.html new file mode 100644 index 0000000000..317ecc8b69 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/date/now/index.html @@ -0,0 +1,101 @@ +--- +title: Date.now() +slug: Web/JavaScript/Reference/Global_Objects/Date/now +tags: + - Date + - JavaScript + - Method + - polyfill + - 参考 + - 方法 + - 时间 +translation_of: Web/JavaScript/Reference/Global_Objects/Date/now +--- +
{{JSRef}}
+ +

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

+ +
{{EmbedInteractiveExample("pages/js/date-now.html")}}
+ +

语法

+ +
var timeInMs = Date.now();
+
+ +

返回值

+ +

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

+ +

描述

+ +

因为 now() 是 {{jsxref("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 的值,取决于这两个值中哪一个更大,也就是,精度更低一些。

+ +

Polyfill

+ +

该方法在 ECMA-262 第五版中被标准化,可以通过下面的代码端来兼容那些不支持该方法的引擎:

+ +
if (!Date.now) {
+  Date.now = function now() {
+    return new Date().getTime();
+  };
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范版本规范状态说明
{{SpecName('ES5.1', '#sec-15.9.4.4', 'Date.now')}}{{Spec2('ES5.1')}}初始定义。在 JavaScript 1.5 中实现
{{SpecName('ES6', '#sec-date.now', 'Date.now')}}{{Spec2('ES6')}} 
+  
+ +

浏览器兼容性

+ + + +

{{Compat("javascript.builtins.Date.now")}}

+ +

参见

+ + -- cgit v1.2.3-54-g00ecf