In my Java Script app I have the date stored in a format like so:
2011-09-24
Now when I try using the above value to create a new Date object (so I can retrieve the date in a different format), the date always comes back one day off. See below:
var doo = new Date("2011-09-24");
console.log(doo);
logs:
Fri Sep 23 2011 20:00:00 GMT-0400 (Eastern Daylight Time)
The best way to handle this without using more conversion methods,
Now just add GMT in your date or you can append it.
Live: https://jsfiddle.net/gajender/2kop9vrk/1/
Notice that Eastern Daylight Time is
-4 hours
and that the hours on the date you're getting back are20
.which is midnight of 2011-09-24.
You're getting the right date, you just never specified the correct time zone.
If you need to access the date values, you can use
getUTCDate()
or any of the othergetUTC*()
functions:It means
2011-09-24 00:00:00 GMT
, and since you're atGMT -4
, it will be20:00
the previous day.Personally, I get
2011-09-24 02:00:00
, because I'm living atGMT +2
.The following worked for me -
To normalize the date and eliminate the unwanted offset (tested here : https://jsfiddle.net/7xp1xL5m/ ):
This also accomplishes the same and credit to @tpartee (tested here : https://jsfiddle.net/7xp1xL5m/1/ ):
If you want to get hour 0 of some date in the local time zone, pass the individual date parts to the
Date
constructor.