I need a way to detect the timezone of a given date object. I do NOT want the offset, nor do I want the full timezone name. I need to get the timezone abbreviation.
Updated for 2015:
jsTimezoneDetect can be used together with moment-timezone to get the timezone abbreviation client side:
moment.tz(new Date(), jstz.determine().name()).format('z'); //"UTC"
Moment-timezone cannot do this on it's own as its function which used to handle this was depreciated because it did not work under all circumstances: https://github.com/moment/moment/issues/162 to get the timezone abbreviation client side.
moment-timezone includes an undocumented method .zoneAbbr()
which returns the time zone abbreviation. This also requires a set of rules which are available to select and download as needed.
Doing this:
<script src="moment.js"></script>
<script src="moment-timezone.js"></script>
<script src="moment-timezone-data.js"></script>
<script>
moment().tz("America/Los_Angeles").zoneAbbr();
</script>
Returns:
'PDT' // As of this posting.
Evan Czaplicki has worked on a draft proposal to add a time zone API to browsers.
I know the problem remains of differences between browsers, but this is what I used to get in Chrome. However it is still not an abbreviation because Chrome returns the long name.
new Date().toString().replace(/^.*GMT.*\(/, "").replace(/\)$/, "")
Not possible with vanilla JavaScript. Browsers are inconsistent about returning timezone strings. Some return offsets like +0700
while others return PST
.
It's not consistent or reliable, which is why you need 3rd party script like moment.js
(and moment-timezone.js
) or create your own hashtable to convert between offsets and timezone abbreviations.
Try Google's Closure Class goog.i18n.DateTimeSymbols and their locale related classes.
This works perfectly in Chrome, Firefox but only mostly in IE11. In IE11, timezones without straight forward abbreviations like "Indian Chagos Time" will return "ICT" instead of the proper "IOT"
var result = "unknown";
try{
// Chrome, Firefox
result = /.*\s(.+)/.exec((new Date()).toLocaleDateString(navigator.language, { timeZoneName:'short' }))[1];
}catch(e){
// IE, some loss in accuracy due to guessing at the abbreviation
// Note: This regex adds a grouping around the open paren as a
// workaround for an IE regex parser bug
result = (new Date()).toTimeString().match(new RegExp("[A-Z](?!.*[\(])","g")).join('');
}
console.log(result);
Result:
"CDT"