javascript date - preserve timezone offset

人走茶凉 提交于 2019-12-19 18:29:21

问题


I have a ISO8601 date that contains a timezone offset (see below). When I create a Date object from this, the date object is converted into my timezone (currently GMT), and timezone offset goes to 0. Is there any way to get the Date() constructor to preserve the timezone offset?

  var date = new Date("2012-01-17T12:55:00.000+01:00");
  console.log(date.toString());

The output I get is:

"Tue Jan 17 2012 11:55:00 GMT+0000 (GMT)"

The output I want is:

"Tue Jan 17 2012 12:55:00"

回答1:


Not with the built-in Date object, as they're only aware of Local (as defined by the user's browser and/or OS settings) and UTC. You can see this from the many cloned methods the class has (e.g., getHours / getUTCHours).

getTimezoneOffset is the only timezone info you really have, but it's local as well and will probably only give you +0 again (or +6 in my case):

var date = new Date("2012-01-17T12:55:00.000+01:00");
console.log(date.getTimezoneOffset() / 60.0);

You can try timezone-js (or one of its forks), but you'll need to know the Olson timezone name not just the GMT/UTC offset:

var date = new new timezoneJS.Date('2012-01-17T12:55:00.000+01:00', 'Europe/Brussels');
alert(date.getTimezoneOffset() / 60.0); // +1


来源:https://stackoverflow.com/questions/8883362/javascript-date-preserve-timezone-offset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!