← 中文资源

简体中文版本

DateTimeFormat 字段窄化与 resolvedOptions

formatToParts 返回 Intl.DateTimeFormatPart 数组,按 part.type 窄化后挑出 year/month/day;resolvedOptions 报告实际生效的 locale、日历与时区。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

{"year":"2026","month":"11","day":"23"}
en-CA UTC gregory

实现说明

重复被限制在 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);