Question

The below function works fine on Chrome, FF and IE11. However I cant get it to work on IE 10. The split returns undefined when I try to split the returned string.

Here is my function:

var now = new Date(), timezoneOffset;

timezoneOffset = now.toString().split('GMT')[1];
timezoneOffset = timezoneOffset.split(' ')[0];
timezoneOffset = timezoneOffset.substr(0, 3) + ':' + timezoneOffset.substr(3, 2);

return timezoneOffset;

So the returned values are: (it could be different depending on your location)

  1. now = Tue May 06 2014 15:31:03 GMT+0300 (EEST)
  2. timezoneOffset (after first split) = +0300 (EEST)
  3. timezoneOffset (after second split) = +0300
  4. timezoneOffset (after substr and adding colon) = +03:00

On fiddle you can put an alert after timezoneOffset = now.toString().split('GMT')[1]; to see the error on IE10

JSFiddle

Était-ce utile?

La solution

You're making the false assumption that now.toString() contains "GMT", let's see what is actually given (for me anyway) in IE;

"Tue May 6 13:48:08 UTC+0100 2014"

Notice no GMT, but a UTC.

This means split_result[1] is undefined, so timezoneOffset is undefined and hence your error

Unable to get property 'split' of undefined or null reference

This isn't the best way to get the timezone's offset anyway, as we're already provided with a method for just that

date.getTimezoneOffset(); // offset in minutes i.e. for me it is -60

Now you can convert this number to your desired formatting;

var o = date.getTimezoneOffset();
var x = Math.abs(o),
    sign = (x === o ? '-' : '+' ),
    m = x % 60,
    h = (x - m) / 60;
m = (m < 10 ? '0' : '') + m;
h = (h < 10 ? '0' : '') + h;

return sign + h + ':' + m;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top