Creating a RelativeTimeFormat Instance
You'll learn how to create an Intl.RelativeTimeFormat object with locale and formatting options to control how relative time strings like "2 days ago" appear.
What Is a RelativeTimeFormat Instance?
Just as Intl.NumberFormat formats numbers and Intl.DateTimeFormat formats dates, Intl.RelativeTimeFormat formats relative time expressions. Think of it as a tool that transforms numeric values and time units into natural language like "in 3 hours" or "5 minutes ago."
To use this formatting power, you first create an instance by calling the constructor with optional locale and configuration options.
Basic Syntax
const rtf = new Intl.RelativeTimeFormat(locale, options);
The locale specifies the language (e.g., 'en', 'es', 'fr'). The options object lets you control formatting behavior.
Key Options
numeric
Controls whether to use numeric output or words when possible:
'always'(default): Always use numbers →"in 1 day"'auto': Use words when natural →"tomorrow"
const rtfNumeric = new Intl.RelativeTimeFormat('en', { numeric: 'always' });
const rtfAuto = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
style
Controls output verbosity:
'long'(default):"in 3 days"'short':"in 3 days"(may abbreviate in some locales)'narrow':"in 3d"(most compact)
const rtfLong = new Intl.RelativeTimeFormat('en', { style: 'long' });
const rtfNarrow = new Intl.RelativeTimeFormat('en', { style: 'narrow' });
Combining Options
const rtf = new Intl.RelativeTimeFormat('en', {
numeric: 'auto',
style: 'long'
});
This instance will format relative times in English, using words like "yesterday" when appropriate, in a verbose style.
Key Takeaway: Create an Intl.RelativeTimeFormat instance with locale and options (numeric and style) to customize how relative time expressions are formatted for different languages and contexts.