Handling a new date (dateString) in Javascript

Can someone explain why formatting the same dateString differently gives a different date?

 > new Date("04/08/1984") <ยท Sun Apr 08 1984 00:00:00 GMT-0600 (Mountain Daylight Time) > new Date("1984-04-08") <ยท Sat Apr 07 1984 18:00:00 GMT-0600 (Mountain Daylight Time) 
+7
javascript
source share
2 answers

When you create a new Date object that passes the dateString constructor to the constructor, it is parsed using Date.parse() . Now, quoting from the MDN documentation (emphasis mine):

Differences in Estimated Time Zone

Given the date string "March 7, 2014" (or "03/07/2014" ), parse() assumes a local time zone , but given an ISO format such as "2014-03-07" , it will accept the UTC time zone . Therefore, Date objects created using these strings will represent different points in time if the system is not installed with the local UTC time zone.

Therefore, since you specify the second line in ISO format, and your local time zone is UTC + 6 , you get a date that is six hours behind you, because it is calculated as UTC +0 . Actually:

 Apr 07 1984 18:00:00 = Apr 08 1984 00:00:00 - 06:00:00 

The mystery is solved!

+6
source share

Your problem is that you add 0 in front of the numbers in "1984-04-08" . "1984-04-08" Try the following:

 new Date("1984-4-8") 

 document.write(new Date("04/08/1984")); document.write("<br>"); document.write(new Date("1984-4-8")); 
+1
source share

All Articles