Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 208
garyewe Avatar asked Oct 02 '11 21:10

garyewe


1 Answers

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)
like image 114
Tomasz Nurkiewicz Avatar answered Sep 29 '22 17:09

Tomasz Nurkiewicz