gpt4 book ai didi

javascript - (新日期 ('2012-12-01' )).getMonth() === 10?

转载 作者:数据小太阳 更新时间:2023-10-29 05:10:37 27 4
gpt4 key购买 nike

(new Date('2012-12-01')).getMonth()10 而不是 11 ( getMonth 是从 0 开始索引的)。我已经在 Firefox、Chrome 和 Node.js 上进行了测试。为什么会这样?

最佳答案

您遇到时区问题。您的 JS 引擎将字符串解释为 UTC,因为它没有进一步指定。来自specification of Date.parse (由 new Date 使用):

The String may be interpreted as a local time, a UTC time, or a time in some other time zone, depending on the contents of the String. The function first attempts to parse the format of the String according to the rules called out in Date Time String Format (15.9.1.15). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.

在您所在的时区,日期时间是 Nov 30 2012 19:00:00 GMT-0500 - 十一月。使用 .getUTCMonth()你会得到十二月。但是,永远不要相信 Date.parse,每个浏览器的处理方式都不一样。因此,如果您不在像 Node.js 这样的受限环境中,您应该始终解析您的字符串(例如使用正则表达式)并将其提供给 new Date(Date.UTC(year, month, date, …)).

关于javascript - (新日期 ('2012-12-01' )).getMonth() === 10?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14311779/

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