Files
Homelab-manager/web/src/utils/date.ts
T
bobbanandClaude Sonnet 5.5 3945c60681 Make the wall display and Proxmox dates follow the date and time settings
The wall clock, date line and 'Updated' footer used the browser locale, and the
Proxmox backup tasks and PBS page used toLocaleString. They now use the display
settings via new formatDate/formatTime helpers.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-16 21:02:41 +02:00

66 lines
2.5 KiB
TypeScript

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";
}
/**
* Parses a timestamp the server stored. SQLite's own `current_timestamp` ("2026-10-02 20:27:55") is UTC but carries no
* zone marker, and `new Date()` would read that as local time — showing every entry shifted by the viewer's UTC offset.
* Timestamps the app wrote itself are ISO strings with a zone and parse as they are.
*/
export function parseDbTimestamp(value: string): Date {
return new Date(/[zZ]|[+-]\d{2}:?\d{2}$/.test(value) ? value : `${value.replace(" ", "T")}Z`);
}
function pad(n: number): string {
return String(n).padStart(2, "0");
}
/** The date part alone, in the chosen date format ("2026-10-16", "16/10/2026" or "10/16/2026"). */
export function formatDate(date: Date): string {
const year = date.getFullYear();
const month = pad(date.getMonth() + 1);
const day = pad(date.getDate());
switch (current.dateFormat) {
case "dmy":
return `${day}/${month}/${year}`;
case "mdy":
return `${month}/${day}/${year}`;
case "ymd":
default:
return `${year}-${month}-${day}`;
}
}
/** The time part alone, on the chosen 12- or 24-hour clock; seconds are left out when `withSeconds` is false (a wall clock, say). */
export function formatTime(date: Date, withSeconds = true): string {
const minutes = pad(date.getMinutes());
const seconds = withSeconds ? `:${pad(date.getSeconds())}` : "";
if (current.timeFormat === "12h") {
const hour24 = date.getHours();
const period = hour24 >= 12 ? "PM" : "AM";
return `${hour24 % 12 || 12}:${minutes}${seconds} ${period}`;
}
return `${pad(date.getHours())}:${minutes}${seconds}`;
}
/** 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 {
return `${formatDate(date)} ${formatTime(date)}`;
}