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)
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. ThereforeDate
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With