如何使用 date-fns-tz 检测时区缩写?

pro*_*ogx 9 javascript timezone date-formatting momentjs date-fns

我想打印时区缩写,例如:IST、UTC、PST、MST、CST、EST 等...

我正在将代码从 momentJS 迁移到 date-fns 并遇到以下问题。当我使用 momentJS 时,一切都按预期工作。例如,下面的代码将打印“ IST

const timeZone = 'Asia/Calcutta';
moment.tz(new Date(), timeZone).format('z'); // IST
Run Code Online (Sandbox Code Playgroud)

使用 MomentJS 的演示

现在,我使用date-fns 的代码可以工作,但不能完全工作,因为它打印“印度标准时间”,而我只想打印IST

format(parisDate, 'zzzz', { timeZone: 'Asia/Calcutta', locale: enGB }); // India Standard Time
Run Code Online (Sandbox Code Playgroud)

谁能告诉我我错过了什么或做错了什么?这是我的代码的现场演示:date-fns DEMO

ant*_*iom 4

检查 的代码后date-fns-tz发现,它本身并不生成时区缩写,而是使用浏览器的 Intl API。时区缩写因区域设置而异。“en-US”或“en-GB”等区域设置不包含 IST 作为时区缩写,而“en-IN”包含。因此,您需要

import enIN from 'date-fns/locale/en-IN'
Run Code Online (Sandbox Code Playgroud)

然后将其作为您format通话中的第三个参数传递,即

import { utcToZonedTime, format } from "date-fns-tz";
const timeZone = "Asia/Kolkata"
const zoneString = format(utcToZonedTime(new Date(), timeZone), "zzz", {
  timeZone,
  locale: enIN
});
Run Code Online (Sandbox Code Playgroud)

然而,这并不能保证其他缩写(例如 CET)适用于建议的语言环境