1

When I try this it produces NaN

const date1 = new Date('29/11/2021');
const date2 = new Date('30/11/2021');
const diffTime = Math.abs(date2 - date1);

but this works

const date1 = new Date('7/13/2010');
const date2 = new Date('12/15/2010');
const diffTime = Math.abs(date2 - date1);

Could someone please explain why?

I got the code from this question but when I tried it with my dates it didn't work

  • 2
    That date format is Month/Day/Year. There is no month 29 or 30. – 001 Nov 29 '21 at 21:41
  • Because there is no `29`th month – Andy Ray Nov 29 '21 at 21:41
  • _“Note: Parsing of date strings with the `Date` constructor (and `Date.parse`, which works the same way) is **strongly discouraged** due to browser differences and inconsistencies.”_ — From the [documentation](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#parameters). – Sebastian Simon Nov 29 '21 at 21:42
  • As someone who learned to write Day/Month/Year I can see how it is confusing to adapt to Month/Day/Year. See: https://stackoverflow.com/questions/59000132/date-format-for-spanish-speakers-returning-nan-or-invalid-date The trick is in considering the user's "locale" – AGE Nov 29 '21 at 21:50
  • https://stackoverflow.com/questions/33299687/how-to-convert-dd-mm-yyyy-string-into-javascript-date-object – epascarello Nov 29 '21 at 22:34

1 Answers1

-1

Actually, producing NaN is browser dependant. Some browsers could understand new Date('29/11/2021') as 29 monthes = 12+12+5 => May 11 2023

To be sure you could use more parsing friendly

new Date('November 29, 2021');

or even

new Date(2021, 10, 29); // its important, that in such constructor form months start from 0
  • "*To be sure you could use more parsing friendly…*" No, don't suggest that. `new Date(2021, 11, 29)` is for 29 December 2021, not November (though suggesting to call the constructor directly is good). ;-) – RobG Nov 30 '21 at 01:33
  • sure, forget to mention, that monthes in this form started from 0 – Andrej Denisov Nov 30 '21 at 07:42