Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 360
pdunker Avatar asked Apr 07 '26 03:04

pdunker


2 Answers

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.

like image 151
DhruvPathak Avatar answered Apr 08 '26 22:04

DhruvPathak


The second Date constructor you use is intended to parse a (known) string representation of a date, like "Dec 25, 1995". The format you pass in is not a standard one, so even though the result is close to the correct date (and could be fixed by correcting the month value, as pointed out by DhruvPathak), it should not be used as results my differ depending on the runtime/browser.

like image 23
dr_barto Avatar answered Apr 08 '26 22:04

dr_barto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!