Intl DateTime And RelativeTime

Render dates for a locale and turn instants into relative phrases with Intl.DateTimeFormat and RelativeTimeFormat.

JavascriptData Integrity

Code

javascriptsnippet
22 lines
const now = new Date('2026-11-17T12:00:00Z');
const later = new Date('2026-11-17T15:30:00Z');

// 绝对时间:语言标签决定顺序与格式
const fmt = new Intl.DateTimeFormat('de-DE', {
  dateStyle: 'medium',
  timeStyle: 'short',
  timeZone: 'UTC',
});
console.log('de-DE:', fmt.format(later));

// 相对时间:按单位与数值生成短语
const rel = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
const diffMinutes = Math.round((later - now) / 60000);
console.log('relative:', rel.format(diffMinutes, 'minute'));
console.log('past:', rel.format(-2, 'day'));

// 时长分片:把毫秒拆成小时与分钟
const h = Math.floor(diffMinutes / 60);
const m = diffMinutes % 60;
const parts = new Intl.ListFormat('en', { type: 'unit', style: 'short' });
console.log('parts:', parts.format([`${h} hr`, `${m} min`]));

Output

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

de-DE: 17.11.2026, 15:30
relative: in 210 minutes
past: 2 days ago
parts: 3 hr, 30 min

How it works

Module-level bindings hold the data — now, later, fmt, rel — with no function scope in between.

Putting it to use

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

Core lines

const parts = new Intl.ListFormat('en', { type: 'unit', style: 'short' });
const rel = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
const fmt = new Intl.DateTimeFormat('de-DE', {
dateStyle: 'medium',
timeStyle: 'short',
timeZone: 'UTC',
});

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. Its state lives in module-level bindings: `now`, `later`, `fmt`.