import { getConfig } from '../hooks/useApi'; function locale(): string | undefined { const value = getConfig().locale; return value || undefined; } function toDate(value: string | number | Date | null | undefined): Date | null { if (value === null || value === undefined || value === '') return null; const date = value instanceof Date ? value : new Date(value); return Number.isNaN(date.getTime()) ? null : date; } /** "28 Nov 2026, 14:05" in the viewer's time zone. */ export function dateTime(value: string | number | Date | null | undefined): string { const date = toDate(value); if (!date) return 'Not set'; return date.toLocaleString(locale(), { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit', }); } /** "Fri 28 Nov, 14:05" for deadlines close to now. */ export function shortDateTime(value: string | number | Date | null | undefined): string { const date = toDate(value); if (!date) return 'Not set'; return date.toLocaleString(locale(), { weekday: 'short', day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit', }); } /** "28 Nov 2026". */ export function dateOnly(value: string | number | Date | null | undefined): string { const date = toDate(value); if (!date) return 'Not set'; return date.toLocaleDateString(locale(), { day: 'numeric', month: 'short', year: 'numeric' }); } /** MySQL DATETIME stored in UTC ("2026-11-28 14:05:00") to a Date. */ export function fromMysqlUtc(value: string | null | undefined): Date | null { if (!value) return null; return toDate(`${value.replace(' ', 'T')}Z`); } /** "3 hours ago", "in 2 days". */ export function relative(value: string | number | Date | null | undefined, now: number = Date.now()): string { const date = toDate(value); if (!date) return ''; const diff = date.getTime() - now; const abs = Math.abs(diff); const units: Array<[Intl.RelativeTimeFormatUnit, number]> = [ ['day', 86_400_000], ['hour', 3_600_000], ['minute', 60_000], ]; const format = new Intl.RelativeTimeFormat(locale(), { numeric: 'auto' }); for (const [unit, ms] of units) { if (abs >= ms || unit === 'minute') { return format.format(Math.round(diff / ms), unit); } } return ''; } /** "5 h 20 min" for a remaining duration in minutes. */ export function duration(minutes: number): string { const total = Math.max(0, Math.round(minutes)); const days = Math.floor(total / 1440); const hours = Math.floor((total % 1440) / 60); const mins = total % 60; if (days > 0) return hours > 0 ? `${days} d ${hours} h` : `${days} d`; if (hours > 0) return mins > 0 ? `${hours} h ${mins} min` : `${hours} h`; return `${mins} min`; } export function plural(count: number, one: string, many: string): string { return `${count} ${count === 1 ? one : many}`; } export function titleCase(value: string): string { const text = value.replace(/_/g, ' '); return text.charAt(0).toUpperCase() + text.slice(1); }