4

Basically my requirement is to compare server passed date with user selected date and display the validation for the same.

I was trying to convert server date in to Javascript date object and I found some wired behavior,

enter image description here

Can someone help me understnad why it make this difference if I flip the format from yyyy-mm-dd to mm-dd-yyyy?

Rockstar
  • 2,228
  • 3
  • 20
  • 39

2 Answers2

0

Looks like the first example is parsing the date string as if it's in UTC (4 hours away from your local timezone?) and then when you print it it gets converted back.

The second format is parsed assuming it's in your local timezone, so midnight local time and printed the same.

Without a format specified, JavaScript has make guesses based on the string it's given. It's making a different choice for those two strings.

It thinks you mean 2018-04-30 UTC in the first case, and when it prints back in your local timezone it's four hours earlier than the second case which it thinks is 2018-04-30 UTC-4.

There's a note on MDN about avoiding parsing date/time strings using the Date constructor and the Date.parse function because of this ambiguity, you may get different behaviour across different browsers.

brabster
  • 42,504
  • 27
  • 146
  • 186
0

If you use / to separate the time, the error will not occur. ie: MM/DD/YYYY, Date time format works differently in different browser.

enter image description here

Md. Abu Taher
  • 17,395
  • 5
  • 49
  • 73