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

如何通过JavaScript Intl获取带缩写与偏移量的全时区信息

基于JavaScript Intl获取时区缩写与偏移量的方法

确实可以通过Intl API的DateTimeFormat对象来获取指定时区的缩写(如PDT/PST)和偏移量(如UTC−07:00)。需要注意的是,时区的缩写和偏移量会随夏令时/冬令时切换而变化,因此结果是基于具体日期计算的(默认使用当前日期)。

获取时区偏移量

使用Intl.DateTimeFormat配合formatToParts方法,通过指定timeZoneName参数为longOffset(长格式偏移)或shortOffset(短格式偏移)来提取偏移信息:

const timeZone = 'America/Los_Angeles';
// 初始化格式化器,指定时区和偏移格式
const offsetFormatter = new Intl.DateTimeFormat('en-US', {
  timeZone: timeZone,
  timeZoneName: 'longOffset' // 可选'shortOffset'获取如"UTC-7"的短格式
});
// 拆分格式化结果,提取偏移量部分
const offset = offsetFormatter.formatToParts().find(part => part.type === 'timeZoneName').value;
console.log(offset); // 输出类似"UTC−07:00"(取决于当前日期是否为夏令时)

获取时区缩写

时区缩写(如PDT/PST)可以通过将timeZoneName参数设置为short来获取(long参数会返回时区全称,如"Pacific Daylight Time"):

const timeZone = 'America/Los_Angeles';
const abbrFormatter = new Intl.DateTimeFormat('en-US', {
  timeZone: timeZone,
  timeZoneName: 'short'
});
const abbreviation = abbrFormatter.formatToParts().find(part => part.type === 'timeZoneName').value;
console.log(abbreviation); // 输出PDT或PST,取决于当前日期

提示:建议使用英文语言环境(如'en-US')来获取标准缩写,非英文环境可能返回本地化的时区名称而非缩写。

批量处理所有支持的时区

结合Intl.supportedValuesOf('timeZone')返回的时区列表,可以批量生成每个时区的缩写和偏移量信息:

// 获取所有支持的时区
const allTimeZones = Intl.supportedValuesOf('timeZone');

// 定义工具函数,返回指定时区的缩写和偏移量
function getTimeZoneDetails(timeZone, date = new Date()) {
  // 获取偏移量
  const offsetFormatter = new Intl.DateTimeFormat('en-US', {
    timeZone: timeZone,
    timeZoneName: 'longOffset'
  });
  const offset = offsetFormatter.formatToParts(date).find(p => p.type === 'timeZoneName').value;

  // 获取缩写
  const abbrFormatter = new Intl.DateTimeFormat('en-US', {
    timeZone: timeZone,
    timeZoneName: 'short'
  });
  const abbreviation = abbrFormatter.formatToParts(date).find(p => p.type === 'timeZoneName').value;

  return { timeZone, abbreviation, offset };
}

// 批量生成所有时区信息
const allTimeZoneDetails = allTimeZones.map(getTimeZoneDetails);
console.log(allTimeZoneDetails);

如果需要获取特定日期的时区信息,只需给getTimeZoneDetails传入目标Date对象即可,比如:

const winterDate = new Date('2024-01-01'); // 冬令时日期
const laWinterInfo = getTimeZoneDetails('America/Los_Angeles', winterDate);
console.log(laWinterInfo); // 此时会返回PST和UTC−08:00

内容的提问来源于stack exchange,提问作者Sudhakar B

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:15:25