How to show time ago
Short answer
Intl.RelativeTimeFormat turns a number and a unit into a phrase in the needed language. Negative numbers mean the past:
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
console.log(rtf.format(-5, 'minute'));
console.log(rtf.format(2, 'day'));
console.log(rtf.format(-1, 'day'));Output:
5 minutes ago
in 2 days
yesterdayChoosing the unit
Calculate the difference in seconds and choose the largest suitable unit:
const units = [
['year', 31536000],
['month', 2592000],
['day', 86400],
['hour', 3600],
['minute', 60],
['second', 1],
];
const timeAgo = (date, now = new Date()) => {
const seconds = Math.round((date - now) / 1000);
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
for (const [unit, size] of units) {
if (Math.abs(seconds) >= size || unit === 'second') {
return rtf.format(Math.round(seconds / size), unit);
}
}
};
const now = new Date(2025, 5, 10, 12, 0);
console.log(timeAgo(new Date(2025, 5, 10, 11, 45), now));
console.log(timeAgo(new Date(2025, 5, 7, 12, 0), now));
console.log(timeAgo(new Date(2025, 5, 10, 15, 0), now));Output:
15 minutes ago
3 days ago
in 3 hoursCommon mistake
Calculating ago and in by hand quickly gets complicated in other languages, where word forms depend on the number. Let Intl do it:
const rtf = new Intl.RelativeTimeFormat('ru');
console.log(rtf.format(-1, 'hour'), '|', rtf.format(-3, 'hour'), '|', rtf.format(-5, 'hour'));Output:
1 час назад | 3 часа назад | 5 часов назадFunctions used in this recipe
- Intl.RelativeTimeFormat — Formats relative time: 3 days ago, in 1 hour.