gpt4 book ai didi

javascript - Firefox new Date() 适用于无效日期

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

当我在 Firefox 控制台中运行它时:

新日期('25/04/2016')

它创建以下日期:

日期 2018-01-04T05:00:00.000Z

它似乎试图从 01/04/2016 开始添加 25 个月并在 01/04/2018 结束。这是预期的行为吗?我本以为它会导致错误,而不是试图解析一个无意义的日期。

Chrome 返回无效日期。

最佳答案

进一步说明 - 当使用带有单个字符串参数的 Date 构造函数时,这等同于使用 Date.parse。

发件人:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

invalid values in date strings not recognized as ISO format as defined by ECMA-262 may or may not result in NaN, depending on the browser and values provided, e.g.:

// Non-ISO string with invalid date values
new Date('23/25/2014');

will be treated as a local date of 25 November, 2015 in Firefox 30 and an invalid date in Safari 7.

原回答如下:

这确实是 Firefox 中的预期行为。

发件人:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Note: Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0, 70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a date for 2013-03-01T01:10:00.

根据评论建议更新:

来自同一来源的更多文档:

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies

所以,是的,当您使用字符串时,不同的浏览器 = 不同的结果,因此不鼓励这样做。

关于javascript - Firefox new Date() 适用于无效日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36462585/

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