如何使用JavaScript仅通过时区偏移值获取对应的时区缩写
解决方案
前提说明
注意:时区偏移值和时区缩写不存在严格的一一对应关系。同一个偏移值可能对应多个地区的不同时区缩写,例如
-06:00既可以对应北美中部标准时间CST,也可以对应北美山地夏令时间MDT,还可能对应其他国家的时区命名,需要结合业务场景的地区范围做筛选。
方案1:使用原生Intl API(无需第三方依赖,自动适配夏令时)
用ECMAScript内置的Intl.DateTimeFormat接口可以直接根据日期和偏移值匹配对应时区缩写,代码如下:
function getTimezoneAbbreviation(datetimeStr) { // 1. 解析输入字符串的时区偏移部分 const offsetMatch = datetimeStr.match(/([+-]\d{2}:\d{2})$/); if (!offsetMatch) return null; const targetOffset = offsetMatch[1]; const date = new Date(datetimeStr); // 2. 遍历所有支持的时区,匹配对应偏移的缩写 const supportedTimezones = Intl.supportedValuesOf('timeZone'); for (const tz of supportedTimezones) { // 获取当前时区在指定日期的偏移字符串 const offsetFormatter = new Intl.DateTimeFormat('en-US', { timeZone: tz, timeZoneName: 'longOffset' }); const currentOffset = offsetFormatter.format(date).match(/([+-]\d{2}:\d{2})$/)?.[0]; if (currentOffset !== targetOffset) continue; // 获取对应时区缩写 const abbrFormatter = new Intl.DateTimeFormat('en-US', { timeZone: tz, timeZoneName: 'short' }); const formatParts = abbrFormatter.formatToParts(date); const tzAbbr = formatParts.find(part => part.type === 'timeZoneName')?.value; if (tzAbbr) return tzAbbr; } return null; } // 测试 console.log(getTimezoneAbbreviation("2020-09-18T15:10:10-06:00")); // 输出示例:MDT(2020年9月属于北美夏令时,-06:00对应山地夏令时)
方案2:手动映射表(适合固定业务场景,性能更高)
如果你的业务只涉及固定的几个时区,不需要适配所有地区,可以直接维护偏移到缩写的映射表,性能更高,结果可控:
// 可根据业务需求自行补充映射关系 const offsetAbbrMap = { "-10:00": "HST", "-09:00": "HDT", "-08:00": "PST", "-07:00": "PDT", "-06:00": "CST", "-05:00": "EST", "-04:00": "EDT", "+00:00": "UTC", "+08:00": "CST" }; function getAbbrByOffset(datetimeStr) { const offset = datetimeStr.slice(-6); return offsetAbbrMap[offset] ?? "未知时区"; } // 测试 console.log(getAbbrByOffset("2020-09-18T15:10:10-06:00")); // 输出:CST
注意事项
- 如果需要限定地区范围,可以在遍历
supportedTimezones时过滤对应地区的时区ID,比如只保留America/*开头的时区,可以避免匹配到其他国家的同名缩写。 - 如果你需要非英文的时区缩写,只需要把
Intl.DateTimeFormat的第一个参数en-US替换为对应语言的locale即可。
内容的提问来源于stack exchange,提问作者Tris
相关产品推荐
相关产品推荐

