javascript - 阅读时刻完整时区名称

标签 javascript typescript timezone momentjs

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

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

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

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

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

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

最佳答案

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,英语,美国太平洋时区)

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

换句话说,对于英语和欧洲/柏林,它将返回“中欧标准时间”“中欧夏令时间” code>,但不仅仅是“中欧时间”

关于javascript - 阅读时刻完整时区名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59003087/

相关文章:

javascript - 从浏览器获取客户端时区

javascript - 删除 Google Maps API v3 中未完成的多边形/折线

javascript - Jest - 监视嵌套的 promise (axios)

c# - 我可以用 java(type)script 异步实现 c# 任务吗?

javascript - 读取 Deno 中记录到控制台的值

r - R strptime/as.POSIXct中的未知时区名称

Python(日期时间)时区转换关闭 4 分钟

javascript - Select2 更改事件 - 在第一个 select2 框值更改时更改下一个 select2 框的选项

javascript - 切换复选框仅选中,不取消选中

Typescript - 确保 id 存在于数组中