使用 moment.js 格式化日期时间以显示时区

Format datetime with moment.js to show timezone

我在使用 moment.js 显示时区时遇到问题。

我试过这个代码:

var result = moment(someDate).format("MM/DD/YYYY HH:mm A Z");

并且我得到 return,例如:08/05/2015 06:18 PM +02:00,这很好,但我希望我的输出像 08/05/2015 06:18 PM WEDT 或类似的东西,带有时区缩写。

尝试使用此代码,但最后我得到的是空时区:

var result = moment(someDate).format("MM/DD/YYYY HH:mm A z"); 

var result = moment(someDate).format("MM/DD/YYYY HH:mm A zz");

更新

正如@Matt Johnson 所建议的那样,我使用这种方法使用 moment-timezone-with-data.js and tzdetect.js:

来显示时区
var tzName = tzdetect.matches()[0];
var result = moment.tz(myDate, tzName).format("MM/DD/YYYY h:mm A zz");

如所述in the documentation

Note: as of 1.6.0, the z/zz format tokens have been deprecated. Read more about it here.

普遍的问题是浏览器无法通过一致的 API 提供时区缩写。为了提供它们,必须有外部数据源。

您可能想研究使用 moment-timezone 插件。它提供时区信息,包括缩写。您必须知道您正在使用的特定时区。例如:

moment.tz("2015-08-05T00:00:00+01:00", "Europe/London").format("MM/DD/YYYY hh:mm A z");
// "08/05/2015 12:00 AM BST"

此外,您不应将 HH(24 小时制的小时数)与 A(12 小时制 am/pm 指示符)混用。使用 hhA,或者使用 HH 而不使用 A

要将 UTC 日期时间转换为用户的当前时区,解决方案是使用 moment-timezone 而不是时刻。(我们在数据库中将所有日期都设置为 UTC)。其他时区也不应该成为问题。

const timeZoneString = Intl.DateTimeFormat().resolvedOptions().timeZone
const getFormattedDateTimeWithTZ = (date) => {
      return moment((date)).tz(timeZoneString).format('ddd, MMM DD YYYY, h:mm A zz')
}
// outputs Tue, Mar 08 2022, 4:00 PM PKT
getFormattedDateTimeWithTZ('2022-03-08T03:00:00.000-08:00')