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/