Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

javascript - Get timezone abbreviation using offset value

Using moment.js (with moment-timezone), I want to get the timezone abbreviation (e.g. PST) for the current locale.

var now = Date.now(); // 1423254073931
var zone = moment(now).zone(); // 480
var timezone = 

How do I get the timezone abbreviation? All of the examples I have seen in the docs and elsewhere pick a specific region like "America/New_York".

From the docs, it looks like I can get the information out of the Zone Object with zone.abbr(timestamp) but I'm not sure how to access the zone object.

JSFiddle

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The title and the question are different. In the title, you ask how to get it using the offset - which would not be possible. There are many time zones that share the same offset, so it isn't possible to distinguish a time zone abbreviation from an offset alone.

But in the question, you asked how to get the abbreviation for the current locale, for a specific timestamp.

The general problem is, there is no fully-reliable way to detect the current time zone. This is discussed in this answer. So moment-timezone can't deterministically tell which time zone should be loaded by default.

There are some other options available though.

Current browsers / node

In current browsers, the ECMAScript Internationalization API extensions are supported on the toLocaleString function of the Date object. When supported, you can do this:

    var d = new Date(); // or whatever date you have
    var tzName = d.toLocaleString('en', {timeZoneName:'short'}).split(' ').pop();

In current browsers, you'll get a value like "EST". You might want to do some sort of tests though, because it won't work in all browsers.

Use jsTimeZoneDetect

You could use a script like jsTimeZoneDetect to guess at the local time zone. It's usually correct, but not guaranteed. You could then pass that value to moment-timezone.

    var tzName = jstz.determine().name();
    var m = moment();
    var abbr = m.tz(tzName).zoneAbbr();  // or .format('z')

Use moment-timezone

There is also now built-in support for time zone detection/guessing in moment-timezone:

    var tzName = moment.tz.guess();
    var abbr = m.tz(tzName).zoneAbbr();  // or .format('z')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...