Back to results for “Time & Internationalization (Intl API)”
JavaScript › Date, Time & Internationalization (Intl API)

How do you get a relative time string like '3 days ago' using built-in APIs?

Advanced

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.

Common follow-ups: How would you compute the numeric offset needed for RelativeTimeFormat from two Date objects?