formatRelativeTime
Muestra tiempo relativo legible como 'hace 2 días'.
#intl
#formatting
#date
#utility
export const formatRelativeTime = (date: Date, base = new Date()) => { const diffSec = Math.round((date.getTime() - base.getTime()) / 1000); const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' }); const divisions: [number, Intl.RelativeTimeFormatUnit][] = [ [60, 'second'], [60, 'minute'], [24, 'hour'], [7, 'day'], [4.34524, 'week'], [12, 'month'], [Number.POSITIVE_INFINITY, 'year'], ]; let unit: Intl.RelativeTimeFormatUnit = 'second'; let value = diffSec; for (const [amount, u] of divisions) { if (Math.abs(value) < amount) { unit = u; break; } value /= amount; } return rtf.format(Math.round(value), unit);};
// Usageconst pastDate = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000);formatRelativeTime(pastDate); // "2 days ago"
const future = new Date(Date.now() + 3600000);formatRelativeTime(future); // "in 1 hour"