javascript date - 保留时区偏移

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8883362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:52:24  来源:igfitidea点击:

javascript date - preserve timezone offset

javascriptdatetimetimezone

提问by Kevin

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?

我有一个包含时区偏移量的 ISO8601 日期(见下文)。当我由此创建 Date 对象时,日期对象被转换为我的时区(当前为 GMT),时区偏移量变为 0。有没有办法让 Date() 构造函数保留时区偏移量?

  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"

回答by Jonathan Lonowski

Not with the built-in Dateobject, 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).

不是内置Dateobject,因为它们只知道Local(由用户的浏览器和/或操作系统设置定义)和UTC。您可以从该类具有的许多克隆方法(例如getHours/ getUTCHours)中看到这一点。

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

getTimezoneOffset是您真正拥有的唯一时区信息,但它也是本地的,并且可能只会+0再次给您(或在我的情况下为 +6):

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 namenot just the GMT/UTC offset:

您可以尝试timezone-js(或其中一个 fork),但您需要知道Olson 时区名称,而不仅仅是 GMT/UTC 偏移量:

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