Format dates as relative time
JavaScript
// Render a timestamp as "3 days ago" style text with Intl.RelativeTimeFormat.
const STEPS = [
['year', 365 * 24 * 60 * 60],
['month', 30 * 24 * 60 * 60],
['day', 24 * 60 * 60],
['hour', 60 * 60],
['minute', 60],
['second', 1],
];
function timeAgo(date, now = Date.now()) {
const diff = (new Date(date).getTime() - now) / 1000; // negative means past
const formatter = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
for (const [unit, seconds] of STEPS) {
if (Math.abs(diff) >= seconds) {
return formatter.format(Math.round(diff / seconds), unit);
}
}
return formatter.format(0, 'second');
}
console.log(timeAgo(Date.now() - 45 * 60 * 1000)); // 45 minutes ago
console.log(timeAgo(Date.now() + 2 * 24 * 60 * 60 * 1000)); // in 2 days