Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

ajax - Annoying javascript timezone adjustment issue

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

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

So this is the CET summer time right now.

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:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Everything is fine, try this:

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

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

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.

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

However current day of month in UTC is:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...