如何在TypeScript中获取'Europe/Berlin'格式的时区字符串?
获取IANA时区标识符(如'Europe/Berlin')的方法
原生Date对象确实没有直接返回IANA时区字符串的方法,timezoneOffset仅能提供当前时区与UTC的分钟偏移量,无法反向映射到具体时区——多个时区可能共享相同偏移,尤其是夏令时切换期间。
以下是在TypeScript中获取IANA时区标识符的可靠方案:
使用Intl.DateTimeFormat API
这是标准内置API,现代浏览器和Node.js均支持,TypeScript无需额外配置即可使用:
function getIanaTimezone(): string { return Intl.DateTimeFormat().resolvedOptions().timeZone; } // 调用示例 const currentTimezone = getIanaTimezone(); console.log(currentTimezone); // 输出示例:'Europe/Berlin'
说明
Intl.DateTimeFormat().resolvedOptions()返回的对象包含timeZone属性,其值为当前运行环境的IANA时区标识符。- 兼容性:Chrome 24+、Firefox 29+、Node.js 10+均支持该API,TypeScript的标准类型定义已覆盖相关接口。
- 若需兼容极老旧环境,可引入
@formatjs/intl-datetimeformat等polyfill,但多数现代项目无需此操作。
内容的提问来源于stack exchange,提问作者Makuna
相关产品推荐
相关产品推荐

