← 中文资源

简体中文版本

formatToParts 重组 ISO 时间戳

DateTimeFormat.formatToParts 把格式化结果拆成类型化字段,过滤掉 literal 后重组出 ISO 时间戳;resolvedOptions 报告实际选用的 locale、日历与计数系统。

阅读英文原文

运行结果

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

{"day":"23","month":"11","year":"2026","hour":"18","minute":"05"}
rebuilt ISO: 2026-11-23T18:05Z
resolved: en-US medium gregory latn

实现说明

演示用的数据放在这几个模块级绑定中:stamp、parts、byType、resolved。

使用要点

  • 演示输出是带标签的(rebuilt ISO:、resolved:),每个操作都会留下自己的一行标注。

常见问题

运行之前需要装什么吗?

不需要——用到的每个 API 都随语言运行时自带,无需安装。 跨调用保留的状态放在这些顶层绑定里:stamp、parts、byType。

核心语句

const resolved = new Intl.DateTimeFormat('en-US', { dateStyle: 'medium', timeZone: 'UTC' }).resolvedOptions();
const byType = Object.fromEntries(parts.filter((p) => p.type !== 'literal').map((p) => [p.type, p.value]));
const parts = new Intl.DateTimeFormat('en-GB', {
  year: 'numeric', month: '2-digit', day: '2-digit',
  hour: '2-digit', minute: '2-digit', timeZone: 'UTC',
}).formatToParts(stamp);

代码示例

const stamp = new Date('2026-11-23T18:05:00Z');
const parts = new Intl.DateTimeFormat('en-GB', {
  year: 'numeric', month: '2-digit', day: '2-digit',
  hour: '2-digit', minute: '2-digit', timeZone: 'UTC',
}).formatToParts(stamp);
const byType = Object.fromEntries(parts.filter((p) => p.type !== 'literal').map((p) => [p.type, p.value]));
console.log(JSON.stringify(byType));
console.log('rebuilt ISO:', `${byType.year}-${byType.month}-${byType.day}T${byType.hour}:${byType.minute}Z`);

// resolvedOptions 暴露实际生效的区域、日历与计数系统
const resolved = new Intl.DateTimeFormat('en-US', { dateStyle: 'medium', timeZone: 'UTC' }).resolvedOptions();
console.log('resolved:', resolved.locale, resolved.dateStyle, resolved.calendar, resolved.numberingSystem);