恼人的JavaScript时区调整问题 [英] Annoying javascript timezone adjustment issue

查看:216
本文介绍了恼人的JavaScript时区调整问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了一个JSON的获取来自服务器的当前时间。例如:

I have set up a JSON that fetches the current time from server. For example:

{
  "myservertime": "2011-10-02T23:00+02:00"
}

所以这是CET夏季现在。

So this is the CET summer time right now.

现在,我也有一个jQuery code解析这非常好。

Now, I also have a jQuery code that parses that very well.

$.sysTime = function(success) {

            $.ajax({
                url: '/jsontimepath/',
                dataType: 'json',
                async: false,
                success: function(json){
                    sysDateTime = new Date(Date.parse(json.myservertime));
                    console.log('The system time now is: ' + sysDateTime)
                }
            });

            return sysDateTime;
        };  

现在的问题是,当我检查它仍然显示错误的时间控制台...它仍然是受我的电脑...例如的时区,在香港的用户,上面引述的时候会导致:

The problem is that when I check the console it still shows wrong time... It is still affected by the timezone of my computer... For example, for a user in Hong Kong, the time quoted above would result:

周一2011年10月3日05:00:00 GMT + 0800(HKT)

Mon Oct 03 2011 05:00:00 GMT+0800 (HKT)

我给它一个有效的ISO8601时间字符串,它只是调节了。实际的时间是回报是正确的(在时区)...但是为什么它调整它像在于:我想它返回CET时间不是本地时间......

I do give it a valid ISO8601 time string and it just adjusts it. The actual time is returns is correct (in that timezone)... But why does it adjust it like that??? I want it to return CET time not the local time...

推荐答案

一切都很好,试试这个:

Everything is fine, try this:

new Date(Date.parse("2011-10-02T23:00+02:00")).getUTCHours()  //21

日期正确解析(服用时区考虑如预期)。然而,当你简单地打印与Date.toString()它显示了在当前浏览器时区的日期(爪哇罪的一个日期对象恬不知耻地复制到JavaScript的...)

The date is parsed correctly (taking the timezone into account as expected). However when you simply print Date.toString() it shows the date in current browser timezone (one of the sins of Java Date object shamelessly copied to JavaScript...)

如果你坚持 getUTC *()系列的方法,你会得到正确的值(如上面的例子中)。普通得到*()方法总是受到浏览器的时区(而不是从你分析的日期,这是失去了时区),因此往往形同虚设。

If you stick to getUTC*() family of methods you will get correct values (like in example above). The ordinary get*() methods are always affected by browser timezone (and not the timezone from the date you parsed, which is lost), hence often useless.

又如: 2011-10-03 02:00 + 03:00 的实际上是23点在十月2日。但是,当你分析它(我目前的浏览器时区+0200(CEST)):

Another example: the 2011-10-03 02:00+03:00 is actually 23:00 on 2nd of October. But when you parse it (my current browser time zone is +0200 (CEST)):

new Date(Date.parse("2011-10-03T02:00+03:00"))  //Oct 03 01:00:00 GMT+0200

一个月的UTC但是当前日期是:

However current day of month in UTC is:

new Date(Date.parse("2011-10-03T02:00+03:00")).getUTCDate()  //2 (2nd of Oct)

这篇关于恼人的JavaScript时区调整问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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