Intl.DateTimeFormat Formats Dates Per Locale

Render dates through Intl.DateTimeFormat so field order, month names, and range collapsing come from the locale rules instead of hand-written format strings.

JavascriptCli Tooling

Code

javascriptsnippet
24 lines
// 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));

Output

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

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

How the snippet works

Top-level bindings launch, en, de, parts hold the demo state — nothing sits inside a function scope.

Using it

The demo output is labeled (en-US :, de-DE :, parts :), so every printed line maps back to its originating operation.

Key statements

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',
});

Interactive Tools for This Topic

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: `launch`, `en`, `de`.