How do you get a relative time string like '3 days ago' using built-in APIs?
Short answer
Intl.RelativeTimeFormat generates locale-correct relative phrases from a numeric offset and unit, without manually building strings like 'X days ago'.
Advertisement
AModel answer
Intl.RelativeTimeFormat generates locale-correct relative phrases from a numeric offset and unit, without manually building strings like 'X days ago'.
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
console.log(rtf.format(-3, 'day')); // '3 days ago'
console.log(rtf.format(1, 'day')); // 'tomorrow'Real-world example
Showing 'Posted 2 hours ago' style timestamps in a social feed or comment section.
Likely follow-ups
- How would you compute the numeric offset needed for RelativeTimeFormat from two Date objects?
Related topics