DateTimeFormat Parts With Typed Narrowing

formatToParts yields Intl.DateTimeFormatPart objects that narrow on part.type, and resolvedOptions reports the exact locale, calendar, and hour cycle chosen.

TypescriptData Fetching

Code

typescriptsnippet
19 lines
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);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

From source to printed result

for (const part of parts) is the loop that performs the per-item work on each pass.

Top-level bindings fmt, wanted, resolved hold the demo state — nothing sits inside a function scope.

Watch out for

  • The project can run it without a single addition beforehand.

Key statements

const wanted = ['year', 'month', 'day'] as const;

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `fmt`, `wanted`, `resolved`.