JavaScript日期 - 保留时区偏移 [英] javascript date - preserve timezone offset

查看:200
本文介绍了JavaScript日期 - 保留时区偏移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我得到的输出是:

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

我想要的输出是:

"Tue Jan 17 2012 12:55:00"


推荐答案

不与内置的 Date object ,因为他们只知道 本地 (由用户浏览器和/或操作系统设置定义)和 UTC 。您可以从类中的许多克隆方法中看到(例如, getHours / getUTCHours )。

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 是您真正拥有的唯一时区信息,但它是本地也可能只会再次给您 +0 (或我的情况下为+6):

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

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

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

这篇关于JavaScript日期 - 保留时区偏移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆