JS protip: Formatting a time distance
By Christophe Porteneuve • Published on 28 October 2022
• 2 min
Cette page est également disponible en français.
After a protip on formatting dates and times two days ago and another one on formatting date/time ranges yesterday, let’s wrap that topic with today’s protip on formatting time distances!
Intl.RelativeTimeFormat
Lesser-known than DateTimeFormat, RelativeTimeFormat has been available for a good while too, allowing us to express times relative to now, as time distances in the past or future.
Unfortunately, it doesn’t use Date objects as “targets,”, but a quantity and a standard unit, which remains quite useful.
The constructor allows the same locales argument as DateTimeFormat (and the entire Intl API, really), and we can use up to two options:
stylecan be'long'(default value, showing the full unit name),'short'(abbreviated unit) et'narrow'(further abbreviation if the locale features it)numericcan be'always'(default value, resulting in numeric distance no matter what) or'auto'(which I like more, using colloquial phrasing for close-enough distances).
Check it out:
const regularFR = new Intl.RelativeTimeFormat('fr-FR')
const shortUS = new Intl.RelativeTimeFormat('en-US', { style: 'short' })
const autoUS = new Intl.RelativeTimeFormat('en-US', { numeric: 'auto' })
const regularDE = new Intl.RelativeTimeFormat('de-DE')
const autoDE = new Intl.RelativeTimeFormat('de-DE', { numeric: 'auto' })
regularFR.format(1, 'day') // => 'dans 1 jour'
regularFR.format(-2, 'days') // => 'il y a 2 jours'
regularFR.format(3, 'weeks') // => 'dans 3 semaines'
regularFR.format(-1, 'month') // => 'il y a 1 mois'
shortUS.format(1, 'day') // => 'in 1 day'
shortUS.format(-2, 'days') // => '2 days ago'
shortUS.format(3, 'weeks') // => 'in 3 wk.'
shortUS.format(-1, 'month') // => '1 mo. ago'
autoUS.format(1, 'day') // => 'tomorrow'
autoUS.format(1, 'week') // => 'next week'
autoUS.format(-1, 'month') // => 'last month'
regularDE.format(1, 'day') // => 'in 1 Tag'
regularDE.format(-1, 'months') // => 'vor 1 Monat'
autoDE.format(1, 'day') // => 'morgen'
autoDE.format(1, 'week') // => 'nächste Woche'
Amazeballs. 😎
Want to dive further?
You’re in luck: we had a protip on date/time formatting, and on date/time range formatting already!
Where can I use that?
Well, everywhere. Taking into account everything in this 3-protips series, you’re good to go with any browser released in, say, the past 3 years, plus Node 13+ and Deno 1.8+. So go for it!
Protips galore!
We got tons of articles, with a lot more to come. Also check out our kick-ass training courses 🔥!