Creating a RelativeTimeFormat Instance
You'll learn how to construct an Intl.RelativeTimeFormat object with locale and formatting options to display human-friendly relative time strings.
The Core Idea
Just like you created NumberFormat and DateTimeFormat instances before, you create a RelativeTimeFormat instance by calling its constructor with a locale string and an options object. This instance then becomes a reusable formatter that converts numeric time values (like "-2" days or "3" hours) into natural-language phrases like "2 days ago" or "in 3 hours."
Think of it as setting up a translator that knows how to say "yesterday" or "next week" in any language, with control over the formality and precision of the output.
The Constructor Syntax
const rtf = new Intl.RelativeTimeFormat(locales, options);
Locales can be a string like 'en-US' or an array of locale identifiers.
Options is an object with three key properties:
numeric:'always'(default) or'auto'. With'auto', you might get "yesterday" instead of "1 day ago".style:'long'(default),'short', or'narrow'. Controls verbosity ("3 months ago" vs "3 mo. ago").localeMatcher: Usually left at default'best fit'.
// Auto-style with "yesterday" instead of "1 day ago"
const rtf1 = new Intl.RelativeTimeFormat('en', {
numeric: 'auto',
style: 'long'
});
// Always numeric, short style
const rtf2 = new Intl.RelativeTimeFormat('fr', {
numeric: 'always',
style: 'short'
});
You now have formatter instances ready to transform time values into locale-appropriate strings.
Key Takeaway: Construct RelativeTimeFormat with locale and options (numeric, style) to create a reusable formatter that converts numeric time differences into natural, localized phrases.