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



如何通过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));

您可以使用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; }

使用moment,您需要覆盖zoneName函数,以使用zz令牌。

参考-https://momentjs.com/timezone/docs/#/using-时区/格式化/

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>

相关内容

  • 没有找到相关文章