(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?
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.
moment(). format('YYYY-MM-DD'); Calling moment() gives us the current date and time, while format() converts it to the specified format.
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).
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, …))
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With