Intl.DateTimeFormat中dayPeriod参数不同取值返回结果一致的问题
问题原因及解决方案
你遇到的问题核心在于英语(en)locale的CLDR(Unicode通用区域数据仓库)定义以及Intl.DateTimeFormat的默认行为:
- 当仅指定
dayPeriod而不搭配其他时间组件(如hour)时,enlocale的默认格式会统一返回完整的时段短语(比如"in the morning"),不会区分narrow/short/long样式。 - 只有当
dayPeriod与hour等时间组件结合使用时,不同样式的差异才会体现出来——这符合CLDR对英语时段格式的定义。
验证示例
搭配hour参数后,就能看到不同dayPeriod样式的区别:
// long样式:返回完整短语 const formatLong = new Intl.DateTimeFormat('en', { hour: 'numeric', hourCycle: 'h12', dayPeriod: 'long' }); console.log(formatLong.format(new Date(2024, 0, 1, 9, 57))); // "9 in the morning" // short样式:返回缩写格式 const formatShort = new Intl.DateTimeFormat('en', { hour: 'numeric', hourCycle: 'h12', dayPeriod: 'short' }); console.log(formatShort.format(new Date(2024, 0, 1, 9, 57))); // "9 AM" // narrow样式:返回更紧凑的缩写 const formatNarrow = new Intl.DateTimeFormat('en', { hour: 'numeric', hourCycle: 'h12', dayPeriod: 'narrow' }); console.log(formatNarrow.format(new Date(2024, 0, 1, 9, 57))); // "9 A"
单独获取dayPeriod值
如果只想单独获取对应样式的dayPeriod文本,可以使用formatToParts()方法提取指定部分:
const formatter = new Intl.DateTimeFormat('en', { hourCycle: 'h12', dayPeriod: 'short' }); const parts = formatter.formatToParts(new Date(2024, 0, 1, 9, 57)); const dayPeriod = parts.find(part => part.type === 'dayPeriod').value; console.log(dayPeriod); // "AM"
内容的提问来源于stack exchange,提问作者Troy Moreland
相关产品推荐
相关产品推荐

