JavaScript Intl: Relative Time and List Formatting
Quick answer
Intl.RelativeTimeFormat and Intl.ListFormat produce locale-sensitive display phrases for relative time and lists. They do not calculate the elapsed time or translate list items.
How it works
Use new Intl.RelativeTimeFormat(locale,{numeric:"auto"}) to allow idioms such as yesterday; format(value, unit) receives an already computed signed quantity (negative past, positive future). new Intl.ListFormat(locale,{style:"long",type:"conjunction"}) joins strings with localized separators and conjunctions; disjunction uses an or-style relationship. Both provide formatToParts for custom display.
const f=new Intl.RelativeTimeFormat("en",{numeric:"auto"}); console.log(f.format(-1,"day"),f.format(1,"day"));Expected output in Node.js:
yesterday tomorrowThe sign and auto option determine the relative expression.
const f=new Intl.ListFormat("en-US",{style:"long",type:"disjunction"}); console.log(f.format(["tea","coffee"]));Expected output in Node.js:
tea or coffeeDisjunction joins the supplied alternatives without reordering them.
Common mistakes
Do not pass a timestamp directly to RelativeTimeFormat; calculate a quantity and choose a unit first. ListFormat does not translate item names.
Practice
Format a supplied signed day count in English and then switch the locale in manual practice.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Intl: Relative Time and List Formatting — Knowledge Check
Apply the taught concept and predict the output.
What does a negative value mean to RelativeTimeFormat.format?
Which ListFormat type expresses alternatives?
Does RelativeTimeFormat compute a difference from Date.now automatically?
What is the exact console output in JavaScript Intl: Relative Time and List Formatting example 1?
const f=new Intl.RelativeTimeFormat("en",{numeric:"auto"}); console.log(f.format(-1,"day"),f.format(1,"day"));What is the exact console output in JavaScript Intl: Relative Time and List Formatting example 2?
const f=new Intl.ListFormat("en-US",{style:"long",type:"disjunction"}); console.log(f.format(["tea","coffee"]));