Date.prototype.valueOf()

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

¥The valueOf() 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
valueOf()

参数

¥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

valueOf() 方法是 类型强制协议 的一部分。由于 Date 有一个 [Symbol.toPrimitive]() 方法,因此当 Date 对象隐式为 被强制为一个数字 时,该方法始终优先于 valueOf()。然而,Date.prototype[Symbol.toPrimitive]() 仍然在内部调用 this.valueOf()

¥The valueOf() method is part of the type coercion protocol. Because Date has a [Symbol.toPrimitive]() method, that method always takes priority over valueOf() when a Date object is implicitly coerced to a number. However, Date.prototype[Symbol.toPrimitive]() still calls this.valueOf() internally.

Date 对象覆盖 ObjectvalueOf() 方法。Date.prototype.valueOf() 返回日期的时间戳,功能上等同于 Date.prototype.getTime() 方法。

¥The Date object overrides the valueOf() method of Object. Date.prototype.valueOf() returns the timestamp of the date, which is functionally equivalent to the Date.prototype.getTime() method.

示例

¥Examples

使用 valueOf()

¥Using valueOf()

js
const d = new Date(0); // 1970-01-01T00:00:00.000Z
console.log(d.valueOf()); // 0

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看