Sometimes we want to tell the user how long ago (or in how long) an event happened.
We can do this with the RelativeTimeFormat
object built in to JavaScript.
For example:
const relativeTimeFormatter = new Intl.RelativeTimeFormat('en');
relativeTimeFormatter.format(-1, 'day'); // '1 day ago'
relativeTimeFormatter.format(1, 'day'); // 'in 1 day'
relativeTimeFormatter.format(6, 'week'); // 'in 6 weeks'
const frTimeFormatter = new Intl.RelativeTimeFormat('fr');
frTimeFormatter.format(-1, 'day'); // 'il y a 1 jour'
frTimeFormatter.format(1, 'day'); // 'dans 1 jour'
frTimeFormatter.format(6, 'week'); // 'dans 6 semaines'
We can make the string returned even nicer, by passing some options to the call to format
:
const relativeTimeFormatter = new Intl.RelativeTimeFormat('en', {
numeric: 'auto',
});
relativeTimeFormatter.format(-1, 'day'); // 'yesterday'
relativeTimeFormatter.format(1, 'day'); // 'tomorrow'
relativeTimeFormatter.format(6, 'week'); // 'in 6 weeks'
const frTimeFormatter = new Intl.RelativeTimeFormat('fr', {
numeric: 'auto',
});
frTimeFormatter.format(-1, 'day'); // 'hier'
frTimeFormatter.format(1, 'day'); // 'demain'
frTimeFormatter.format(6, 'week'); // 'dans 6 semaines'
See: