gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:10:01 31 4
gpt4 key购买 nike

我正在阅读 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 的行为与其他浏览器不同。

关于javascript - MomentJS - isValid() 方法未正确验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34073381/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com