peppa/packages/shared/src/time.ts

37 lines
1.6 KiB
TypeScript

// PEP-304: the time people read — always in the platform's zone (PEPPA_TZ), never the server's
// (UTC in the containers). No Node modules: the hook's light modules and the browser may use it.
const valid = new Map<string, boolean>();
const zoneOk = (tz: string) => {
let ok = valid.get(tz);
if (ok === undefined) {
try {
new Intl.DateTimeFormat("en-GB", { timeZone: tz });
ok = true;
} catch {
ok = false;
}
valid.set(tz, ok);
}
return ok;
};
/** The platform's time zone for `Intl` (`PEPPA_TZ`), or undefined — the process's own — when unset or not a zone. */
export function platformZone(env: Record<string, string | undefined> = process.env): string | undefined {
const tz = env.PEPPA_TZ?.trim();
return tz && zoneOk(tz) ? tz : undefined;
}
const at = (d: Date | number | string) => (d instanceof Date ? d : new Date(d));
/** «23:35» in the platform's zone. */
export const platformTime = (d: Date | number | string, timeZone = platformZone()) =>
new Intl.DateTimeFormat("ru-RU", { timeZone, hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).format(at(d));
/** «25.11, 23:35» in the platform's zone. */
export const platformDayTime = (d: Date | number | string, timeZone = platformZone()) =>
new Intl.DateTimeFormat("ru-RU", { timeZone, day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).format(at(d));
/** «2026-11-25» — the calendar day in the platform's zone (to compare days). */
export const platformDay = (d: Date | number | string, timeZone = platformZone()) => new Intl.DateTimeFormat("en-CA", { timeZone }).format(at(d));