You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript或moment-timezone.js将时区ID转换为完整时区名称

moment-timezone.js 获取完整时区名称实现方案

moment-timezone 本身未内置输出完整时区名称的API,它底层依赖的IANA时区数据库仅存储了时区缩写、偏移量、时令规则等数据,没有自带多语言的完整时区名称映射,可通过以下两种方案实现需求:

方案一:配合原生Intl API实现(推荐)

无需额外依赖,自动适配时令切换、支持多语言输出:

/**
 * 根据时区ID获取完整时区名称
 * @param {string} tzId IANA时区ID,如'America/Mexico_City'
 * @param {string} lang 输出语言,默认值为'zh-CN',英文可传'en-US'
 * @returns {string} 完整时区名称
 */
function getFullTimeZoneName(tzId, lang = 'zh-CN') {
  const formatter = new Intl.DateTimeFormat(lang, {
    timeZone: tzId,
    timeZoneName: 'long'
  });
  // 提取时区名称部分
  return formatter.formatToParts(new Date())
    .find(part => part.type === 'timeZoneName')
    .value;
}

// 测试用例
console.log(getFullTimeZoneName('America/Mexico_City', 'en-US')); 
// 冬令时输出:Central Standard Time,夏令时输出:Central Daylight Time
console.log(getFullTimeZoneName('Asia/Shanghai', 'zh-CN'));
// 输出:中国标准时间

方案二:纯moment-timezone + 自定义映射表实现

如果项目要求不依赖原生API的输出规则,可以自己维护时区映射表:

// 自定义时区完整名称映射表,可按业务需求补充全所需时区
const tzFullNameMap = {
  'America/Mexico_City': {
    standard: 'Central Standard Time',
    daylight: 'Central Daylight Time'
  },
  'Asia/Shanghai': {
    standard: '中国标准时间',
    daylight: '中国标准时间'
  }
  // 更多时区映射...
};

function getFullTimeZoneNameWithMoment(tzId) {
  const timeZone = moment.tz(tzId);
  // 判断当前是否为夏令时
  const isDst = timeZone.isDST();
  return isDst ? tzFullNameMap[tzId].daylight : tzFullNameMap[tzId].standard;
}

// 测试用例
console.log(getFullTimeZoneNameWithMoment('America/Mexico_City'));

该方案需要自行维护映射表的更新,适配时令、多语言的成本更高。


内容的提问来源于stack exchange,提问作者Ihor Horovyi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 13:15:00