Detect timezone abbreviation using JavaScript

北战南征 提交于 2019-12-17 07:18:21

问题


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. For example, GMT, UTC, PST, MST, CST, EST, etc...

Is this possible? The closest I've gotten is parsing the result of date.toString(), but even that won't give me an abbreviation. It gives me the timezone's long name.


回答1:


If all else fails, you can simply create your own hashtable with the long names and abbreviations.




回答2:


A native solution:

var zone = new Date().toLocaleTimeString('en-us',{timeZoneName:'short'}).split(' ')[2]
console.log(zone)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString




回答3:


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.

Edit (Feb 2018)

Evan Czaplicki has worked on a draft proposal to add a time zone API to browsers.




回答4:


[sorry for how I write English]

Hi, date object doesn't have a method for get the timezone abreviation, but it is implicit there at almost end of the toString return:

for example

var rightNow = new Date();
alert(rightNow);

the output will be something like "Wed Mar 30 2011 17:29:16 GMT-0300 (ART)" so, you can isolate what is between parentheses "ART" that is the timezone abreviation

var rightNow = new Date();
alert(String(String(rightNow).split("(")[1]).split(")")[0]);

the output will be "ART"

it's to late to answer, but I hope it'll be usefull for somebody




回答5:


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"



回答6:


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.




回答7:


For a crossbrowser support I recommend using YUI 3 Library:

Y.DataType.Date.format(new Date(), {format:"%Z"});

It supports strftime identifiers.

For more information: http://yuilibrary.com/yui/docs/datatype/#dates




回答8:


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(/\)$/, "")



回答9:


I was able to achieve this with only moment.

moment.tz(moment.tz.guess()).zoneAbbr() //IST



回答10:


This is a tricky subject. From what I gather the timezone is not embedded as part of the Date object when it's created. You also cannot set the timezone for a Date object. However, there is a timezone offset you can get from a Date object which is determined by the user's host system (timezone) settings. Think of timezone as a way to determine the offset from UTC.

To make life easier, I highly recommend moment and moment-timezone for handling these things. Moment creates a wrapper object for Date with a nice API for all kinds of things.

If an existing date object is supplied to you through some parameter or something, you can pass it the constructor when creating a the moment object and you're ready to roll. At this point you can use moment-timezone to guess the user's timezone name, and then use moment-timezone formatting to get the abbreviation for the timezone. I would venture to say that most users have their timezone set automatically but you shouldn't rely on this for 100% accuracy. If needed you can also set the timezone you want to use manually before pulling the format you need.

In general when working with date and time it's best to store UTC in your database and then use moment js to format the time for the user's timezone when displaying it. There may be cases where you need to be sure the timezone is correct. For example if you are allowing a user to schedule something for a specific date and time. You would need to make absolutely sure that with a west coast user that you set the timezone to PDT/PST before converting to UTC for storage in your database.

Regarding the timezone abbreviation...
Here is a basic example to get the timezone abbreviation using moment and moment-timezone.

// if all you need is the user's timezone abbreviation you don't even need a date object.
const usersTimezoneName = moment.tz.guess()
const timezoneAbbr = moment().tz(usersTimezoneName).format('z')
console.log(timezoneAbbr) // PST (depending on where the user is)

// to manually set the timezone
const newYorkAbbr = moment(dateObj).tz('America/New_York').format('z')
console.log(newYorkAbbr) // EST

For displaying a specific date object with offsets for a specific timezone you can do this.

const xmas = new Date('December 25, 2017 16:20:00')
const losAngelesXmas = moment(xmas).tz('America/Los_Angeles')
console.log(losAngelesXmas.format("dddd, MMMM Do YYYY, h:mm:ss a")) // Monday, December 25th 2017, 4:20:00 pm



回答11:


Try Google's Closure Class goog.i18n.DateTimeSymbols and their locale related classes.




回答12:


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.




回答13:


Here is a JavaScript self-updating, 12-hour format date/time display that doesn't quite answer the question, however it may help others as it is related and builds on Stephen DuMont's solution and MDN link. W3 Schools had a very helpful tutorial, and real-time updates do not require page refresh.

Tests with the latest versions of desktop FireFox, Chrome, Opera, and Internet Explorer 11 all work. The "2-digits" hour only appears to prefix a zero for single values in IE, however the minutes return a 2-digit value reliably for all browsers. Tests with discontinued Windows Safari work although 12-hour format is ignored and seconds are not hidden.

The function includes the local timezone, as well adjustable options for fall-back languages, day and date display, and 12/24 hour format. Date and time were split to add the separating 'at' string. Setting only 'toLocaleTimeString' with select options will also return both date and time. The MDN pages can be referenced for options and values.

<!--
function dateTimeClock() {
  var date = new Date();
  document.getElementById('timedate').innerHTML = date.toLocaleDateString(['en-us', 'en-GB'], {
      weekday: 'long',
      month: 'long',
      day: '2-digit',
      year: 'numeric'
    }) + ' at ' +
    date.toLocaleTimeString(['en-us', 'en-GB'], {
      hour12: 'true',
      hour: '2-digit',
      minute: '2-digit',
      timeZoneName: 'short'
    });
  var t = setTimeout(dateTimeClock, 500);
}

function start() {
  dateTimeClock();
}
window.onload = start;
//-->
<div id="timedate"></div>



回答14:


try {
    result = /.*\s(.+)/.exec(date.toLocaleDateString(navigator.language, {timeZoneName:'short' }))[1];
} catch(e) {
    result = (new Date()).toTimeString().match(new RegExp("[A-Z](?!.*[\(])","g")).join('');
}

console.log(result);


来源:https://stackoverflow.com/questions/1954397/detect-timezone-abbreviation-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!