(new Date('2012-12-01'))。getMonth()=== 10? [英] (new Date('2012-12-01')).getMonth() === 10?

查看:79
本文介绍了(new Date('2012-12-01'))。getMonth()=== 10?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(new Date('2012-12-01'))。getMonth() 10 而不是 11 getMonth 是0索引)。我已经在Firefox,Chrome和Node.js上测试过。为什么会发生这种情况?

(new Date('2012-12-01')).getMonth() is 10 instead of 11 (getMonth is 0-indexed). I've tested on Firefox, Chrome, and Node.js. Why does this happen?

推荐答案

您正在遇到时区问题。您的JS引擎将该字符串解释为UTC,因为它没有进一步指定。从 Date.parse (由 新日期使用):

You are experiencing a timezone issue. Your JS engine interprets the string as UTC, since it was no further specified. From the specification of Date.parse (which is used by new Date):


字符串可能被解释为本地时间,UTC时间或某个其他时区的时间,取决于String的内容。该函数首先尝试根据日期时间字符串格式中调用的规则来解析String的格式( 15.9.1.15 )。如果String不符合该格式,该函数可能会退回到任何实现特定的启发式或实现特定日期格式。

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.

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

In your timezone, the datetime is Nov 30 2012 19:00:00 GMT-0500 - in November. Use .getUTCMonth() and you would get December. However, never trust Date.parse, every browser does it differently. So if you are not in a restricted environments like Node.js, you always should parse your string (e.g. with regex) and feed it to new Date(Date.UTC(year, month, date, …)).

这篇关于(new Date('2012-12-01'))。getMonth()=== 10?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆