← 中文资源

简体中文版本

Intl.DateTimeFormat 按区域渲染日期

日期渲染交给 Intl.DateTimeFormat:字段顺序、月份名、时间段折叠都由区域规则决定,formatToParts 拿到分段可自定义组装,formatRange 自动省略同日重复。

阅读英文原文

运行结果

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

en-US : March 14, 2026 at 9:30 AM
de-DE : 14. März 2026 um 09:30
parts : month=March day=14 year=2026 hour=9 minute=30 dayPeriod=AM
range : March 14, 2026, 9:30 AM – 5:00 PM

实现说明

launch、en、de、parts 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 跑完文件,输出里会留下标记——en-US :、de-DE :、parts :。

常见问题

它依赖第三方库吗?

没有引用任何第三方库,标准库就够了。 状态都挂在模块顶层:launch、en、de。

核心语句

const parts = en.formatToParts(launch).filter((p) => p.type !== 'literal');
const en = new Intl.DateTimeFormat('en-US', {
  dateStyle: 'long',
  timeStyle: 'short',
  timeZone: 'UTC',
});
const de = new Intl.DateTimeFormat('de-DE', {
  dateStyle: 'long',
  timeStyle: 'short',
  timeZone: 'UTC',
});

代码示例

// Intl.DateTimeFormat: 日期渲染规则交给区域设置,而不是手写格式串
const launch = new Date('2026-03-14T09:30:00Z');

const en = new Intl.DateTimeFormat('en-US', {
  dateStyle: 'long',
  timeStyle: 'short',
  timeZone: 'UTC',
});
console.log('en-US :', en.format(launch));

const de = new Intl.DateTimeFormat('de-DE', {
  dateStyle: 'long',
  timeStyle: 'short',
  timeZone: 'UTC',
});
console.log('de-DE :', de.format(launch));

// formatToParts: 拿到字段分段,自定义组装
const parts = en.formatToParts(launch).filter((p) => p.type !== 'literal');
console.log('parts :', parts.map((p) => p.type + '=' + p.value).join(' '));

// formatRange: 同日的两个时刻自动省略重复部分
const end = new Date('2026-03-14T17:00:00Z');
console.log('range :', en.formatRange(launch, end));