【问题标题】:Read Moment Full Timezone Name读取时刻完整时区名称
【发布时间】:2020-03-19 01:09:12
【问题描述】:

MomentJS 提供了一系列开箱即用的强大功能。

通过timezone 插件的其中一个是显示时区的字符串缩写,例如CET

const locationName = moment.tz.guess(true)                       // "Europe/Berlin"
const timezoneInitials = moment.tz(locationName).format('zz')    // "CET"

是否可以从时刻对象中获取 CET 的完整时区名称字符串(即Central European Time)?

如果没有,有什么替代方案?

截至今天,此类解析不可用/记录在案。从List of time zone abbreviations 之类的列表中映射和重复数据删除似乎也不是最优的。

【问题讨论】:

标签: javascript typescript timezone momentjs


【解决方案1】:

Moment 不直接提供此功能。

但是,大多数现代浏览器都支持 ECMAScript 国际化 API,允许您编写如下函数:

function getTimeZoneLongName(date, locale, timeZone) {
  const f = Intl.DateTimeFormat(locale, { timeZone, timeZoneName: 'long' });
  return f.formatToParts(date).find(x => x.type === 'timeZoneName').value;
}

示例用法:

// current date/time, current locale and time zone
getTimeZoneLongName(new Date()) //=> "Pacific Standard Time"

// current date/time, specific locale, current time zone
getTimeZoneLongName(new Date(), "fr") //=> "heure normale du Pacifique nord-américain"

// current date/time, specific locale, specific time zone
getTimeZoneLongName(new Date(), "fr", "Asia/Tokyo") //=> "eure normale du Japon"

// specific date/time, current locale, specific time zone
getTimeZoneLongName(new Date(2020, 5, 1), undefined, "Europe/London") //=> "British Summer Time"

(示例输出来自 Windows 10 上的 Chrome 78,英语,美国太平洋时区)

请注意,这会给出标准时间或夏令时的名称,具体取决于给定日期的有效内容。目前没有办法检索通用名称。

换句话说,对于英语和Europe/Berlin,它将返回"Central European Standard Time""Central European Summer Time",但不仅仅是"Central European Time"

【讨论】:

    猜你喜欢
    • 2015-09-29
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 2018-11-08
    相关资源
    最近更新 更多