import { LOCALE_HTML_LANG, type Locale } from "@/i18n/config";
const MISSING_PLACEHOLDER = "-";
/**
* Falsy values (undefined, null, "", 0, NaN) are treated as "not set" so they
* render as the "-" placeholder instead of a blank cell, 1970 or "NaN".
*/
function isMissing(
value: string | number | undefined | null,
): value is undefined | null | "" | 0 {
return !value;
}
function toDate(value: string | number): Date | null {
const d = new Date(value);
return isNaN(d.getTime()) ? null : d;
}
/**
* Full date + time, per active UI locale. Missing values render as "-";
* non-empty strings that cannot be parsed fall back to the raw value.
*/
export function formatDateTime(
value: string | number | undefined | null,
locale: Locale = "zh",
options: Intl.DateTimeFormatOptions = {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
},
): string {
if (isMissing(value)) return MISSING_PLACEHOLDER;
const d = toDate(value);
if (!d) return typeof value === "string" ? value : MISSING_PLACEHOLDER;
return d.toLocaleString(LOCALE_HTML_LANG[locale], options);
}
/** Time-of-day only, per active UI locale. */
export function formatTimeOfDay(
value: string | number | undefined | null,
locale: Locale = "zh",
options: Intl.DateTimeFormatOptions = {
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
},
): string {
if (isMissing(value)) return MISSING_PLACEHOLDER;
const d = toDate(value);
if (!d) return typeof value === "string" ? value : MISSING_PLACEHOLDER;
return d.toLocaleTimeString(LOCALE_HTML_LANG[locale], options);
}