Is the Javascript date object always one day off?

后端 未结 23 2757
既然无缘
既然无缘 2020-11-22 01: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 obje

23条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 02:14

    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 )  );
    

提交回复
热议问题