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(年,月,日,…)).

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...