pdunker pdunker - 3 months ago 10
Javascript Question

Why are those dates different?

Here the console output:

new Date(2016, 08, 22)
Thu Sep 22 2016 00:00:00 GMT+0200 (CEST)

new Date("2016, 08, 22")
Mon Aug 22 2016 00:00:00 GMT+0200 (CEST)


Different months but why ?

Answer

Javascript months are 0 based in the numeric case, but in the string parsing 08 is mapped to August as it is a string translation of "August" in standard date format. Date is being invoked in different ways as mentioned here

  1. new Date();
  2. new Date(value);
  3. new Date(dateString);
  4. new Date(year,month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);

In your case, 3 & 4 formats are being called.

>> new Date(2016, 08, 22)
>> Thu Sep 22 2016 00:00:00 GMT+0530 (IST)
>> new Date(2016, 01, 22)
>> Mon Feb 22 2016 00:00:00 GMT+0530 (IST)
>> new Date(2016, 0, 22)
>> Fri Jan 22 2016 00:00:00 GMT+0530 (IST)
>> new Date("2016-08-22")
>> Mon Aug 22 2016 05:30:00 GMT+0530 (IST)
>> new Date("2016/08/22")
>> Mon Aug 22 2016 00:00:00 GMT+0530 (IST)
  • @RobG's input from the comments:

...parsing ofstrings other than ISO 8601 extended format is entirely implementation dependent. The result of parsing "2016, 08, 22" could be anything, including an invalid Date.