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

后端 未结 3 1206
梦毁少年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:00

    The error is arising from prefixing the day 01 with 0. Not sure WHY this is, but if you remove the zero before the 1, it gives you the right month (11).

    Also, it starts giving the wrong month at October if that means anything.

    Short term fix, use 1 instead of 01.

    0 讨论(0)
  • 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, …)).

    0 讨论(0)
  • 2021-01-18 09:19

    For Firefox's case, at least, RFC2822 states that date specifications must be separated by Folding White Space. Try (new Date('2012 12 01')).getMonth(); Usage of - as a separator does not appear to be defined.

    0 讨论(0)
提交回复
热议问题