psaxton
psaxton

Reputation: 1843

Javascript new Date(dateString) handling

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)

Upvotes: 8

Views: 753

Answers (2)

Marco Bonelli
Marco Bonelli

Reputation: 69346

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!

Upvotes: 7

A.J. Uppal
A.J. Uppal

Reputation: 19264

Your problem is that you are adding 0 before the numbers in "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"));

Upvotes: 1

Related Questions