(new Date('2012-12-01')).getMonth() === 10?

后端 未结 3 1203
梦毁少年i
梦毁少年i 2021-01-18 08:35

(new Date(\'2012-12-01\')).getMonth() is 10 instead of 11 (getMonth is 0-indexed). I\'ve tested on Firefox, Chrome, and N

3条回答
  •  时光说笑
    2021-01-18 09:02

    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):

    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.

    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, …)).

提交回复
热议问题