如何从Intl.DateTimeFormat中仅获取时区名称?
如何从Intl.DateTimeFormat中仅获取时区名称?
嘿,我懂你为啥犯愁——直接用Intl.DateTimeFormat只指定timeZoneName时,确实会默认带出日期部分,这是API的默认行为,它会自动补充基础日期组件来生成完整的格式化字符串。
你那个用split的办法虽然能临时解决问题,但确实有点“野路子”,万一哪天本地化格式变了(比如某些地区的时区名不是用逗号和日期分隔),代码直接就崩了。给你个更靠谱的方案:用formatToParts()方法。
这个方法会把格式化后的内容拆成一个个带类型标识的对象,你只需要筛选出type为timeZoneName的部分就行,完全不用依赖字符串分割。举个例子:
const now = new Date(); const locale = "en-US"; const timeZone = "America/New_York"; const timeZoneFormatter = new Intl.DateTimeFormat(locale, { timeZoneName: "short", timeZone, }); // 拆分格式化片段,提取时区名称 const timeZoneName = timeZoneFormatter.formatToParts(now) .find(part => part.type === "timeZoneName") .value; console.log('TimeZone 正确获取:', timeZoneName); // 输出 EDT
如果想要长格式的时区名称(比如Eastern Daylight Time),只需要把timeZoneName改成"long"就行。
结合你原来的代码,我补一个完整的示例:
const now = new Date(); const locale = "en-US"; const timeZone = "America/New_York"; //always use HQ local time zone const dateFormatter = new Intl.DateTimeFormat(locale, { weekday: "short", month: "short", day: "numeric", timeZone, }); console.log('Date:', dateFormatter.format(now)); const timeFormatter = new Intl.DateTimeFormat(locale, { hour: "numeric", minute: "numeric", second: "numeric", timeZone, }); console.log('Time:', timeFormatter.format(now)); const timeZoneFormatter1 = new Intl.DateTimeFormat(locale, { timeZoneName: "short", timeZone, }); console.log('TimeZone attempt #1:', timeZoneFormatter1.format(now)); const timeZoneFormatter2 = new Intl.DateTimeFormat(locale, { month: undefined, day: undefined, year: undefined, timeZoneName: "short", timeZone, }); console.log('TimeZone attempt #2:', timeZoneFormatter2.format(now)); const timeZoneFormatter3 = new Intl.DateTimeFormat(locale, { timeZoneName: "short", timeZone, }); console.log('TimeZone attempt #3 (hacky):', timeZoneFormatter2.format(now).split(',')[1].trim()); // 新增的标准方法 const timeZoneFormatter4 = new Intl.DateTimeFormat(locale, { timeZoneName: "short", timeZone, }); const tzName = timeZoneFormatter4.formatToParts(now).find(p => p.type === 'timeZoneName').value; console.log('TimeZone attempt #4 (proper):', tzName);
这个方法完全遵循API设计逻辑,不会因为本地化规则变化而失效,比字符串分割靠谱多啦。
备注:内容来源于stack exchange,提问作者Chris Barr
相关产品推荐
相关产品推荐

