Incorrect timezone name in javascript only in IE

2019-09-19 12:03发布

问题:

I am using the below mentioned code for getting the timezone name/id in the clients timezone. Using the below code I get EDT for United state clients but now when I try it in Indian timezone I get it as UTC instead of IST.

This issue is occurring only for IE all other browsers give me the correct values, how can I get the correct value in IE which is IST?

var now = new Date().toString();
var TZ = now.indexOf('(') > -1 ?
now.match(/\([^\)]+\)/)[0].match(/[A-Z]/g).join('') :
now.match(/[A-Z]{3,4}/)[0];
if (TZ == "GMT" && /(GMT\W*\d{4})/.test(now)) 
TZ = RegExp.$1;
document.write(TZ);

回答1:

Quoting MDN:

The toTimeString() method is especially useful because compliant engines implementing ECMA-262 may differ in the string obtained from toString() for Date objects, as the format is implementation-dependent; simple string slicing approaches may not produce consistent results across multiple engines.

I suggest you try using .toTimeString():

(new Date()).toTimeString().match(/\(([^\)]+)\)/)[1]

I believe that should give you what you want.