实现说明
重复被限制在 for (const part of parts) 里——其余代码按顺序各跑一遍。
顶层就这几处状态:fmt、wanted、resolved。
常见问题
它依赖第三方库吗?
没有引用任何第三方库,标准库就够了。 状态都挂在模块顶层:fmt、wanted、resolved。
核心语句
const wanted = ['year', 'month', 'day'] as const;
代码示例
const fmt = new Intl.DateTimeFormat('en-CA', {
year: 'numeric', month: '2-digit', day: '2-digit', timeZone: 'UTC',
});
const parts: Intl.DateTimeFormatPart[] = fmt.formatToParts(new Date(Date.UTC(2026, 10, 23)));
// 按 part.type 窄化:只要 year/month/day 三段
const wanted = ['year', 'month', 'day'] as const;
type Field = (typeof wanted)[number];
const picked: Partial<Record<Field, string>> = {};
for (const part of parts) {
if ((wanted as readonly string[]).includes(part.type)) {
picked[part.type as Field] = part.value;
}
}
console.log(JSON.stringify(picked));
// resolvedOptions 报告实际生效的区域、日历与时区
const resolved = fmt.resolvedOptions();
console.log(resolved.locale, resolved.timeZone, resolved.calendar);