Date.prototype.getTime()

Date 实例的 getTime() 方法返回该日期自 epoch 以来的毫秒数,epoch 定义为 UTC 1970 年 1 月 1 日开始的午夜。

¥The getTime() method of Date instances returns the number of milliseconds for this date since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC.

Try it

语法

¥Syntax

js
getTime()

参数

¥Parameters

没有任何。

¥None.

返回值

¥Return value

代表该日期的 timestamp(以毫秒为单位)的数字。如果日期是 invalid,则返回 NaN

¥A number representing the timestamp, in milliseconds, of this date. Returns NaN if the date is invalid.

描述

¥Description

Date 对象基本上由 timestamp 表示,并且此方法允许你检索时间戳。你可以使用此方法帮助将日期和时间分配给另一个 Date 对象。该方法在功能上等同于 valueOf() 方法。

¥Date objects are fundamentally represented by a timestamp, and this method allows you to retrieve the timestamp. You can use this method to help assign a date and time to another Date object. This method is functionally equivalent to the valueOf() method.

示例

¥Examples

使用 getTime() 复制日期

¥Using getTime() for copying dates

构造具有相同时间值的日期对象。

¥Constructing a date object with the identical time value.

js
// Since month is zero based, birthday will be January 10, 1995
const birthday = new Date(1994, 12, 10);
const copy = new Date();
copy.setTime(birthday.getTime());

测量执行时间

¥Measuring execution time

减去对新生成的 Date 对象的两个后续 getTime() 调用,给出这两次调用之间的时间跨度。这可以用来计算某些操作的执行时间。另请参阅 Date.now() 以防止实例化不必要的 Date 对象。

¥Subtracting two subsequent getTime() calls on newly generated Date objects, give the time span between these two calls. This can be used to calculate the executing time of some operations. See also Date.now() to prevent instantiating unnecessary Date objects.

js
let end, start;

start = new Date();
for (let i = 0; i < 1000; i++) {
  Math.sqrt(i);
}
end = new Date();

console.log(`Operation took ${end.getTime() - start.getTime()} msec`);

注意:在支持 Performance API 高分辨率时间功能的浏览器中,Performance.now() 可以提供比 Date.now() 更可靠、更精确的经过时间测量。

¥Note: In browsers that support the Performance API's high-resolution time feature, Performance.now() can provide more reliable and precise measurements of elapsed time than Date.now().

规范

Specification
ECMAScript Language Specification
# sec-date.prototype.gettime

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看