(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?
(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?
- It returned 11 (as expected) when I tried it in FF. Which browser are you using? – nnnnnn Commented Jan 14, 2013 at 3:00
- @nnnnnn I don't know what to tell you. It happens in Chrome, Firefox, and Node.js for me. – dbkaplun Commented Jan 14, 2013 at 3:01
- My apologies; thank you for clarifying. I have formulated my answer below. – Ryan Stein Commented Jan 14, 2013 at 3:15
-
Do a
console.log(new Date('2012-12-01'))
. What is it? – Bergi Commented Jan 14, 2013 at 3:17 -
1
@MindVirus: Then it is a timezone issue (at least in your browser, not sure of your node.js server timezone). Use
.getUTCMonth()
– Bergi Commented Jan 14, 2013 at 3:20
3 Answers
Reset to default 7 +50You 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, …))
.
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.
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.