Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

(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?

like image 894
dbkaplun Avatar asked Jan 14 '13 02:01

dbkaplun


People also ask

What does new date () return in JavaScript?

Returns the numeric value corresponding to the current time—the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC, with leap seconds ignored.

How to get current date using moment js?

moment(). format('YYYY-MM-DD'); Calling moment() gives us the current date and time, while format() converts it to the specified format.

What does getMonth return JavaScript?

The getMonth() method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year).


2 Answers

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

like image 61
Bergi Avatar answered Sep 28 '22 08:09

Bergi


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.

like image 31
Ryan Stein Avatar answered Sep 28 '22 06:09

Ryan Stein