Intl.RelativeTimeFormat
The Intl.RelativeTimeFormat object enables language-sensitive relative time formatting. It allows you to format time differences like "yesterday", "in 5 minutes", or "2 days ago" without manually handling pluralization or translation.
1. Basic Usage
The constructor takes two optional arguments: locales and options.
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
console.log(rtf.format(-1, 'day')); // "yesterday"
console.log(rtf.format(0, 'day')); // "today"
console.log(rtf.format(1, 'day')); // "tomorrow"
console.log(rtf.format(-1, 'month')); // "last month"
2. Numeric Option
The numeric option controls whether to use numeric values (e.g., "1 day ago") or special strings (e.g., "yesterday").
always: Always use numeric values.auto: Use special strings when available (default is usuallyalwaysif not specified, butautois often preferred for natural language).
const rtfAlways = new Intl.RelativeTimeFormat('en', { numeric: 'always' });
console.log(rtfAlways.format(-1, 'day')); // "1 day ago"
console.log(rtfAlways.format(1, 'day')); // "in 1 day"
const rtfAuto = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
console.log(rtfAuto.format(-1, 'day')); // "yesterday"
console.log(rtfAuto.format(1, 'day')); // "tomorrow"
3. Style Option
The style option controls the length of the message.
long: "in 1 month" (default)short: "in 1 mo."narrow: "in 1 mo." (similar to short for some locales)
const rtfLong = new Intl.RelativeTimeFormat('en', { style: 'long' });
const rtfShort = new Intl.RelativeTimeFormat('en', { style: 'short' });
const rtfNarrow = new Intl.RelativeTimeFormat('en', { style: 'narrow' });
console.log(rtfLong.format(2, 'quarter')); // "in 2 quarters"
console.log(rtfShort.format(2, 'quarter')); // "in 2 qtrs."
console.log(rtfNarrow.format(2, 'quarter')); // "in 2 qtrs."
4. formatToParts
Returns an array of objects representing the different components of the formatted string.
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
const parts = rtf.formatToParts(-3, 'day');
console.log(parts);
/*
[
{ type: "integer", value: "3", unit: "day" },
{ type: "literal", value: " days ago" }
]
*/
programming/javascript/vanilla/javascript programming/javascript/vanilla/intl-datetimeformat