简体   繁体   English

javascript日期 - 保留时区偏移量

[英]javascript date - preserve timezone offset

I have a ISO8601 date that contains a timezone offset (see below). 我的ISO8601日期包含时区偏移量(见下文)。 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? 当我从中创建一个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"

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 . 不使用内置Date对象 ,因为它们只知道Local (由用户的浏览器和/或OS设置定义)和UTC You can see this from the many cloned methods the class has (eg, getHours / getUTCHours ). 您可以从该类具有的许多克隆方法中看到这一点(例如, 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): 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 name not just the GMT/UTC offset: 您可以尝试使用timezone-js (或其中一个分叉 ),但您需要知道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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM