使用偏移值获取时区缩写 [英] Get timezone abbreviation using offset value

查看:180
本文介绍了使用偏移值获取时区缩写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用moment.js(with moment-timezone),我想得到当前语言环境的时区缩写(例如PST)。

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 = 

如何获得时区缩写?我在文档和其他地方看到的所有示例都选择了一个特定的区域,如America / New_York

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".

从文档中,看起来我可以使用<$从区域对象中获取信息c $ c> zone.abbr(timestamp)但我不知道如何访问区域对象。

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

推荐答案

标题和问题是不同。在标题中,您询问如何使用偏移来获取它 - 这是不可能的。有许多时区共享相同的偏移量,因此无法区分时区缩写和单独的偏移量。

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.


  • 在某些浏览器中, ECMAScript国际化API 扩展日期对象的> toLocaleString 功能。如果支持,你可以这样做(没有时间):

  • In some browsers, the ECMAScript Internationalization API extensions are supported on the toLocaleString function of the Date object. When supported, you can do this (without moment):

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

在支持的浏览器中,您将获得类似EST的值。您可能希望进行某种测试,因为它不适用于所有浏览器。

In supported 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.

您可以使用像 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')


  • 现在还有内置支持用于时刻 - 时区的时区检测/猜测:

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


  • 这篇关于使用偏移值获取时区缩写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆