MomentJS - isValid() 方法未正确验证

MomentJS - isValid() method is not validating correctly

我正在阅读 MomentJS 的文档以验证从字符串创建的时刻日期。

他们给出的例子是:

1) moment("not a real date").isValid(); // false

但是如果我在字符串末尾加 1 并验证它,我得到:

2) moment("not a real date 1").isValid(); // true

为什么 #2 是有效的时刻日期对象?

请注意,该构造函数现在是 deprecated。但要回答这个问题:

这个构造函数反过来将"not a real date 1"字符串传递给Date构造函数。看看这个:

在Chrome中:

new Date("not a real date 1") --> Mon Jan 01 2001 00:00:00 GMT-0600 (Central Standard Time)
new Date("not a real date")   --> Invalid Date

在 IE11 中:

new Date("not a real date 1") --> [date] NaN[date] NaN
new Date("not a real date")   --> [date] NaN[date] NaN

在 FireFox 42 中:

new Date("not a real date 1") --> Invalid Date
new Date("not a real date")   --> Invalid Date

所以答案是,它 正确验证,并且它是一个有效的日期对象,因为 Date 构造函数成功创建了一个 Date 对象。 Date 构造函数中存在错误,至少在某些浏览器中是这样。

编辑:

这是 ECMAScript 6 spec 的相关部分,强调我的:

If Type(v) is String, then Let tv be the result of parsing v as a date, in exactly the same manner as for the parse method (20.3.3.2). If the parse resulted in an abrupt completion, tv is the Completion Record.

然后,20.3.3.2部分:

The function first attempts to parse the format of the String according to the rules (including extended years) called out in Date Time String Format (20.3.1.16). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats. Unrecognizable Strings or dates containing illegal element values in the format String shall cause Date.parse to return NaN.

因此,由于规范明确允许浏览器创造性地解析字符串,我想这不是错误。 Chrome 只是行为与其他人不同。