my pkgs monorepo
at main 25 lines 888 B view raw
1/** 2 * Formats a date string into a relative, human-readable time. 3 * Uses the user's system locale where possible, with a fallback to en-GB. 4 */ 5export function formatRelativeTime(dateString: string): string { 6 const date = new Date(dateString); 7 const now = new Date(); 8 const diffMs = now.getTime() - date.getTime(); 9 const diffMins = Math.floor(diffMs / 60000); 10 const diffHours = Math.floor(diffMins / 60); 11 const diffDays = Math.floor(diffHours / 24); 12 13 if (diffMins < 1) return 'just now'; 14 if (diffMins < 60) return `${diffMins}m ago`; 15 if (diffHours < 24) return `${diffHours}h ago`; 16 if (diffDays < 7) return `${diffDays}d ago`; 17 18 const userLocale = typeof navigator !== 'undefined' ? navigator.language : 'en-GB'; 19 20 return date.toLocaleDateString(userLocale, { 21 day: 'numeric', 22 month: 'short', 23 year: date.getFullYear() !== now.getFullYear() ? 'numeric' : undefined 24 }); 25}