Is the Javascript date object always one day off?

2018-12-31 23:49发布

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)

15条回答
余生请多指教
2楼-- · 2019-01-01 00:25

The best way to handle this without using more conversion methods,

 var mydate='2016,3,3';
 var utcDate = Date.parse(mydate);
 console.log(" You're getting back are 20.  20h + 4h = 24h :: "+utcDate);

Now just add GMT in your date or you can append it.

 var  mydateNew='2016,3,3'+ 'GMT';
 var utcDateNew = Date.parse(mydateNew);
 console.log("the right time that you want:"+utcDateNew)

Live: https://jsfiddle.net/gajender/2kop9vrk/1/

查看更多
谁念西风独自凉
3楼-- · 2019-01-01 00:26

Notice that Eastern Daylight Time is -4 hours and that the hours on the date you're getting back are 20.

20h + 4h = 24h

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 other getUTC*() functions:

var d,
    days;
d = new Date('2011-09-24');
days = ['Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat'];
console.log(days[d.getUTCDay()]);
查看更多
看风景的人
4楼-- · 2019-01-01 00:26

It means 2011-09-24 00:00:00 GMT, and since you're at GMT -4, it will be 20:00 the previous day.

Personally, I get 2011-09-24 02:00:00, because I'm living at GMT +2.

查看更多
皆成旧梦
5楼-- · 2019-01-01 00:28

The following worked for me -

    var doo = new Date("2011-09-24").format("m/d/yyyy");
查看更多
像晚风撩人
6楼-- · 2019-01-01 00:33

To normalize the date and eliminate the unwanted offset (tested here : https://jsfiddle.net/7xp1xL5m/ ):

var doo = new Date("2011-09-24");
console.log(  new Date( doo.getTime() + Math.abs(doo.getTimezoneOffset()*60000) )  );
// Output: Sat Sep 24 2011 00:00:00 GMT-0400 (Eastern Daylight Time)

This also accomplishes the same and credit to @tpartee (tested here : https://jsfiddle.net/7xp1xL5m/1/ ):

var doo = new Date("2011-09-24");
console.log( new Date( doo.getTime() - doo.getTimezoneOffset() * -60000 )  );
查看更多
无色无味的生活
7楼-- · 2019-01-01 00:37

If you want to get hour 0 of some date in the local time zone, pass the individual date parts to the Date constructor.

new Date(2011,08,24); // month value is 0 based, others are 1 based.
查看更多
登录 后发表回答