Relative time without a date library
JavascriptTurns a timestamp into 'three days ago' using the built-in formatter.
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
const DIVISIONS = [
[60, 'second'], [60, 'minute'], [24, 'hour'],
[7, 'day'], [4.34524, 'week'], [12, 'month'],
];
function ago(date) {
let duration = (date - Date.now()) / 1000;
for (const [amount, unit] of DIVISIONS) {
if (Math.abs(duration) < amount) return rtf.format(Math.round(duration), unit);
duration /= amount;
}
return rtf.format(Math.round(duration), 'year');
}