Intl DateTime And RelativeTime
Render dates for a locale and turn instants into relative phrases with Intl.DateTimeFormat and RelativeTimeFormat.
Code
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 minHow 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
Age CalculatorCalculate exact age in years, months, and days between a birth date and a reference date, plus total days and the next birthday countdown.Business Days CalculatorCount the weekdays between two dates, excluding weekends and any holidays you list, and see how many calendar and weekend days are involved.Cron Next Runs CalculatorCompute the next scheduled run times for a standard five-field cron expression, supporting ranges, lists, steps, and day-of-week naming semantics.ISO Week CalculatorFind the ISO 8601 week number, ISO week-year, week start and end dates, and day of year for any calendar date, with strict date validation.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.