function timeAgo(date, locale = 'en') {
const rtf = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });
const diff = (new Date(date) - Date.now()) / 1000;
const units = [
['year', 31536000], ['month', 2592000], ['week', 604800],
['day', 86400], ['hour', 3600], ['minute', 60], ['second', 1],
];
for (const [unit, secs] of units) {
if (Math.abs(diff) >= secs || unit === 'second') {
return rtf.format(Math.round(diff / secs), unit);
}
}
}
// Usage
console.log(timeAgo(Date.now() - 3 * 86400 * 1000)); // "3 days ago"
console.log(timeAgo(Date.now() + 2 * 3600 * 1000)); // "in 2 hours"
Create a free account and build your private vault. Share publicly whenever you want.