实现说明
演示用的数据放在这几个模块级绑定中: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);