import type { DateFormat, TimeFormat } from "../api/client"; export interface DateTimeSettings { dateFormat: DateFormat; timeFormat: TimeFormat; } let current: DateTimeSettings = { dateFormat: "ymd", timeFormat: "24h" }; /** Called once at app startup (and whenever the setting is changed) so every formatDateTime() call site picks it up without prop-drilling. */ export function setDateTimeSettings(settings: DateTimeSettings): void { current = settings; } /** Current 12h/24h preference, for formatters outside this file (e.g. cronstrue's use24HourTimeFormat option). */ export function is24HourFormat(): boolean { return current.timeFormat === "24h"; } function pad(n: number): string { return String(n).padStart(2, "0"); } /** Formats a date using the app-wide date/time display settings (defaults to "YYYY-MM-DD HH:mm:ss" on a 24-hour clock). */ export function formatDateTime(date: Date): string { const year = date.getFullYear(); const month = pad(date.getMonth() + 1); const day = pad(date.getDate()); let datePart: string; switch (current.dateFormat) { case "dmy": datePart = `${day}/${month}/${year}`; break; case "mdy": datePart = `${month}/${day}/${year}`; break; case "ymd": default: datePart = `${year}-${month}-${day}`; break; } const minutes = pad(date.getMinutes()); const seconds = pad(date.getSeconds()); let timePart: string; if (current.timeFormat === "12h") { const hour24 = date.getHours(); const period = hour24 >= 12 ? "PM" : "AM"; const hour12 = hour24 % 12 || 12; timePart = `${hour12}:${minutes}:${seconds} ${period}`; } else { timePart = `${pad(date.getHours())}:${minutes}:${seconds}`; } return `${datePart} ${timePart}`; }