getTime()
方法返回一个时间的格林威治时间数值。
你可以使用这个方法把一个日期时间赋值给另一个Date
对象。这个方法的功能和 valueOf()
方法一样。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
语法
dateObj.getTime()
参数
无。
返回值
getTime
方法的返回值一个数值,表示从1970年1月1日0时0分0秒(UTC,即协调世界时)距离该日期对象所代表时间的毫秒数。
例子
使用 getTime() 复制日期对象
创建一个拥有相同时间值的日期对象。
var birthday = new Date(1991, 9, 17);
var copy = new Date();
copy.setTime(birthday.getTime());
测量代码执行时间
连续调用两个新生成的日期对象的 getTime 方法,根据两次调用的返回值求得时间差。这可以用于计算某些操作的执行时间。避免生成不必要的Date
对象另见Date.now()
var end, start, i;
start = new Date();
for (i = 0; i < 1000; i++) {
Math.sqrt(i);
}
end = new Date();
console.log("Operation took " + (end.getTime() - start.getTime()) + " msec");
规范
规范版本 | 规范状态 | 说明 |
---|---|---|
ECMAScript 1st Edition (ECMA-262) | Standard | 初始定义 |
ECMAScript 5.1 (ECMA-262) Date.prototype.getTime |
Standard | |
ECMAScript 2015 (6th Edition, ECMA-262) Date.prototype.getTime |
Standard |
浏览器兼容性
BCD tables only load in the browser
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.