/** * Formatting Utilities */ /** * Formats a date string or Date object into a readable string. * Example: 'Dec 12, 2024' or 'Dec 12, 2024, 10:30 AM' */ export function formatDate( dateString: string | Date | null | undefined, includeTime = false ): string { if (!dateString) return '-'; try { const date = new Date(dateString); // Check for invalid date if (isNaN(date.getTime())) return '-'; const options: Intl.DateTimeFormatOptions = { year: 'numeric', month: 'short', day: 'numeric', ...(includeTime && { hour: 'numeric', minute: '2-digit', }), }; return new Intl.DateTimeFormat('en-US', options).format(date); } catch (e) { return String(dateString); } } /** * Formats a number as currency (USD by default). * Example: $1,234.56 */ export function formatCurrency( value: number | string | null | undefined, currency = 'USD' ): string { if (value === null || value === undefined) return '-'; const numValue = typeof value === 'string' ? parseFloat(value) : value; if (isNaN(numValue)) return String(value); return new Intl.NumberFormat('en-US', { style: 'currency', currency, }).format(numValue); } /** * Formats bytes into a human readable file size. * Example: 1.2 MB */ export function formatFileSize(bytes: number): string { if (bytes === 0) return '0 Bytes'; const k = 1024; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; } /** * Formats a percentage. * Example: 95.5% */ export function formatPercent(value: number): string { return new Intl.NumberFormat('en-US', { style: 'percent', maximumFractionDigits: 1, }).format(value / 100); // Assuming input is like 95.5, not 0.955 }