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
语法
参数
返回值
描述
¥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.
示例
使用 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.
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 thanDate.now()
.
规范
Specification |
---|
ECMAScript Language Specification # sec-date.prototype.gettime |
浏览器兼容性
BCD tables only load in the browser