如何在js或moment.js中将时区ID转换为时区名称

How to convert time zone id to to time zone name in js or moment.js

如何通过 moment-timezone.js

将时区 ID 转换为时区名称

示例:

const timeZone = moment.tz('America/Mexico_City');
timeZone.zoneAbbr() // CST to Central Standard Time
timeZone.format('z') // CST to Central Standard Time

我需要 Central Standard Time

如果您正在考虑使用普通 ole JavaScript 作为替代方案,只需使用 Intl.DateTimeFormat() 来控制日期或时间显示的任何方面。

像这样:

const time = new Intl.DateTimeFormat("en" , {timeZoneName: "long"});
let date = new Date();
console.log(time.format(date));

使用moment,你需要覆盖zoneName函数,才能使用zz令牌。

参考 - https://momentjs.com/timezone/docs/#/using-timezones/formatting/

const timeZone = moment().tz('America/Mexico_City');

var abbrs = {
    EST : 'Eastern Standard Time',
    EDT : 'Eastern Daylight Time',
    CST : 'Central Standard Time',
    CDT : 'Central Daylight Time',
    MST : 'Mountain Standard Time',
    MDT : 'Mountain Daylight Time',
    PST : 'Pacific Standard Time',
    PDT : 'Pacific Daylight Time',
};

moment.fn.zoneName = function () {
    var abbr = this.zoneAbbr();
    return abbrs[abbr] || abbr;
};

console.log(timeZone.format('zz'));
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>

您可以使用 Date.toLocaleTimeString() 获取时区名称(长格式或短格式):

function getTimeZoneName(timeZone, timeZoneName = 'short') {
    let [,...tz] = new Date().toLocaleTimeString('en', { timeZoneName: "long", timeZone, timeZoneName, hour12: false }).split(' ');
    return tz.join(' '); 
}

let timeZones = ['America/Mexico_City', 'America/Los_Angeles', 'Europe/Berlin'];
for(let timeZone of timeZones) {
    console.log('\nTimezone:', timeZone);
    console.log('Long/Short name:', getTimeZoneName(timeZone, 'long'), '/', getTimeZoneName(timeZone, 'short'));
}
    
.as-console-wrapper { max-height: 100% !important; top: 0; }