范围错误:失效日期

当尝试将无效日期转换为 ISO 日期字符串时,会出现 JavaScript 异常 "失效日期"。

¥The JavaScript exception "invalid date" occurs when an invalid date is attempted to be converted to an ISO date string.

信息

¥Message

RangeError: Invalid time value (V8-based)
RangeError: invalid date (Firefox)
RangeError: Invalid Date (Safari)

错误类型

¥Error type

RangeError

什么地方出了错?

¥What went wrong?

你正在将 失效日期 值转换为 ISO 日期字符串。这通常通过以下三种方式之一发生:

¥You are converting an invalid date value to an ISO date string. This usually happens in one of three ways:

当你尝试解析无效日期字符串或将时间戳设置为越界值时,会生成无效日期。无效日期通常会导致所有日期方法返回 NaN 或其他特殊值。但是,此类日期没有有效的 ISO 字符串表示形式,因此当你尝试这样做时会引发错误。

¥An invalid date is produced when you attempt to parse an invalid date string, or set the timestamp to an out-of-bounds value. Invalid dates usually cause all date methods to return NaN or other special values. However, such dates do not have valid ISO string representations, so an error is thrown when you attempt to do so.

示例

¥Examples

无效案例

¥Invalid cases

js
const invalid = new Date("nothing");
invalid.toISOString(); // RangeError: invalid date
invalid.toJSON(); // RangeError: invalid date
JSON.stringify({ date: invalid }); // RangeError: invalid date

但是,大多数其他方法返回特殊值:

¥However, most other methods return special values:

js
invalid.toString(); // "Invalid Date"
invalid.getDate(); // NaN

有关更多详细信息,请参阅 Date.parse() 文档。

¥For more details, see the Date.parse() documentation.

有效案例

¥Valid cases

js
new Date("05 October 2011 14:48 UTC").toISOString(); // "2011-10-05T14:48:00.000Z"
new Date(1317826080).toISOString(); // "2011-10-05T14:48:00.000Z"

也可以看看