微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – (新日期(‘2012-12-01’)).getMonth()=== 10?

(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 (07002). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.

在您的时区,日期时间是2012年11月30日19:00:00 GMT-0500 – 11月.使用.getUTCMonth(),你会得到12月.但是,永远不要相信Date.parse,每个浏览器都会以不同的方式做到.因此,如果您不在Node.js等受限制的环境中,则应始终解析字符串(例如使用正则表达式)并将其提供给新日期(Date.UTC(年,月,日,…)).

原文地址:https://www.jb51.cc/js/150161.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐