Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript new Date(dateString) handling

Tags:

javascript

Would 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)
like image 261
psaxton Avatar asked Apr 15 '15 20:04

psaxton


1 Answers

When you create a new Date object passing a dateString parameter to the constructor, it gets parsed using the Date.parse() method. Now, quoting from the MDN documentation (emphasis mine):

Differences in assumed time zone

Given a date string of "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 assume a time zone of UTC. Therefore Date objects produced using those strings will represent different moments in time unless the system is set with a local time zone of UTC.

Therefore, since that your are giving the second string in the ISO format, and your local time zone is UTC+6, you're getting a date which is six hour behind yours, because it gets calculated as UTC+0. In fact:

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

Mystery solved!

like image 142
Marco Bonelli Avatar answered Oct 08 '22 01:10

Marco Bonelli