停止javascript日期功能从更改时区偏移 [英] Stop javascript Date function from changing timezone offset

查看:96
本文介绍了停止javascript日期功能从更改时区偏移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有iso日期时间需要从一个字符串转换为日期对象。如何保留日期,将其转换为本地浏览器时区。

So I have iso date time that need to be converted from a string to date object. How do I keep date from converting it to local browser timezone.

new Date('2013-07-18T17:00:00-05:00')
Thu Jul 18 2013 18:00:00 GMT-0400 (EDT)

我想要获得

2013年7月18日17:00:00 GMT-0500(XX)

Thu Jul 18 2013 17:00:00 GMT-0500 (XX)

推荐答案

您不能改变Javascript的这种行为,因为它是Javascript工作的唯一简单方法。发生什么就是Javascript看时间偏移,计算匹配的时间戳,然后在本地时区中询问操作系统的时间戳表示。这里要理解的是, -05:00 不是时区的指示,而是从UTC转变。

You cannot change this behavior of Javascript because it is the only simple way for Javascript to work. What happens is simply that Javascript looks at the time shift, computes the matching timestamp, and then asks the OS for the representation of this timestamp in the local time zone. What is key to understand here is that -05:00 is not an indication of time zone but simply a shift from UTC.

时区是复杂的野兽,只是任意的政治决定。操作系统提供服务以在当地时区显示时间,但不显示在其他时区。要做到这一点,你必须考虑像DST这样几乎是一个地狱的东西。

Time zones are complex beasts that are just arbitrary political decisions. The OS provides a service to display time in the local time zone, but not in other time zones. To do that you have to take in account things like DST that are pretty much a hell.

与时间管理一样,解决这个问题的唯一体面的方法是使用专用库。在Javascript中,您会发现 Moment.js Moment.Timezone.js 非常有帮助。

As always with time management, the only decent way to tackle this problem is to use a dedicated library. In Javascript, you'll find Moment.js and Moment.Timezone.js very helpful.

示例 http://codepen.io/Xowap/pen/XKpKZb?editors=0010

document.write(moment('2013-07-18T17:00:00-05:00').tz('America/New_York').format('LLL'));

作为奖励,您可以从Moment.js获得大量格式/解析功能。

As a bonus, you get a ton of formatting/parsing features from Moment.js.

还请注意,只要您使用ISO 8601,您的日期可以精确定位到一个精确的时刻,从而显示在您喜欢的任何时区。换句话说,JS转换您的日期并不重要。

Please also note that as long as you use the ISO 8601, your date can be pinpointed to a precise moment, and thus be displayed in any timezone of your liking. In other words, JS "converting" your date doesn't matter.

这篇关于停止javascript日期功能从更改时区偏移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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