Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Social Engine & Remote Navigator8 * File : apps/social-web/src/time.ts9 * Module : social-web10 * Repository : https://git.spboucher.ai/maclustr-social11 * Project Website : https://social.spboucher.ai12 * Created : 2026-12-0113 * Last Modified : 2026-12-0114 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Time helpers. Database values are UTC ISO strings; everything shown to a person goes through43// Intl.DateTimeFormat with a named time zone. No offset is ever computed by hand from a table:44// the offset of an instant is always *read back* from Intl.4546export type Civil = { y: number; m: number; d: number; h: number; mi: number };47export const DEFAULT_TZ = 'America/Toronto';4849const cache = new Map<string, Intl.DateTimeFormat>();50function partsFormat(tz: string): Intl.DateTimeFormat {51 let f = cache.get(tz);52 if (!f) { f = new Intl.DateTimeFormat('en-CA', { timeZone: tz, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }); cache.set(tz, f); }53 return f;54}55export function isValidTimeZone(tz: string): boolean { try { new Intl.DateTimeFormat('en', { timeZone: tz }); return true; } catch { return false; } }5657/** Wall-clock reading of a UTC instant in a named zone. */58export function civilInZone(instant: number | Date | string, tz: string): Civil {59 const o: Record<string, number> = {};60 for (const p of partsFormat(tz).formatToParts(new Date(instant))) if (p.type !== 'literal') o[p.type] = Number(p.value);61 return { y: o.year, m: o.month, d: o.day, h: o.hour, mi: o.minute };62}63const asUtc = (c: Civil) => Date.UTC(c.y, c.m - 1, c.d, c.h, c.mi);64const same = (a: Civil, b: Civil) => a.y === b.y && a.m === b.m && a.d === b.d && a.h === b.h && a.mi === b.mi;6566export type ZonedResult =67 | { kind: 'ok'; utc: Date }68 /** The wall-clock time does not exist (clocks jump forward). `before`/`after` are the nearest real instants an hour-shift away. */69 | { kind: 'gap'; before: Date; after: Date }70 /** The wall-clock time happens twice (clocks go back). */71 | { kind: 'overlap'; first: Date; second: Date };7273/**74 * Converts a wall-clock date and time in a named zone to the UTC instant(s) it designates.75 * Method: probe the zone around the target to collect the offsets Intl actually reports there,76 * build one candidate instant per offset, and keep the candidates that Intl formats back to77 * exactly the requested wall-clock time. Zero survivors = DST gap; two = DST overlap.78 */79export function zonedToUtc(c: Civil, tz: string): ZonedResult {80 const target = asUtc(c);81 const H = 3_600_000;82 const candidates = new Set<number>();83 for (const probe of [target - 36 * H, target - 12 * H, target, target + 12 * H, target + 36 * H]) {84 const minute = Math.floor(probe / 60_000) * 60_000;85 const offset = asUtc(civilInZone(minute, tz)) - minute;86 candidates.add(target - offset);87 }88 const all = [...candidates].sort((a, b) => a - b);89 const hits = all.filter((t) => same(civilInZone(t, tz), c));90 if (hits.length === 1) return { kind: 'ok', utc: new Date(hits[0]) };91 if (hits.length >= 2) return { kind: 'overlap', first: new Date(hits[0]), second: new Date(hits[hits.length - 1]) };92 return { kind: 'gap', before: new Date(all[0]), after: new Date(all[all.length - 1]) };93}9495/* ── Civil-date keys (YYYY-MM-DD): pure calendar arithmetic, no zone involved ── */96const pad = (n: number) => String(n).padStart(2, '0');97export const keyOf = (y: number, m: number, d: number) => `${y}-${pad(m)}-${pad(d)}`;98export function parseKey(key: string): { y: number; m: number; d: number } { const [y, m, d] = key.split('-').map(Number); return { y, m, d }; }99export function addDays(key: string, n: number): string { const { y, m, d } = parseKey(key); const t = new Date(Date.UTC(y, m - 1, d + n)); return keyOf(t.getUTCFullYear(), t.getUTCMonth() + 1, t.getUTCDate()); }100/** 0 = Monday … 6 = Sunday. */101export function weekdayMon(key: string): number { const { y, m, d } = parseKey(key); return (new Date(Date.UTC(y, m - 1, d)).getUTCDay() + 6) % 7; }102export function dayKeyInZone(instant: number | Date | string, tz: string): string { const c = civilInZone(instant, tz); return keyOf(c.y, c.m, c.d); }103export function weekOf(key: string): string[] { const start = addDays(key, -weekdayMon(key)); return Array.from({ length: 7 }, (_, i) => addDays(start, i)); }104/** Whole weeks (Monday first) covering the month that contains `key`. */105export function monthGrid(key: string): string[] {106 const { y, m } = parseKey(key);107 const first = keyOf(y, m, 1);108 const last = addDays(keyOf(m === 12 ? y + 1 : y, m === 12 ? 1 : m + 1, 1), -1);109 const start = addDays(first, -weekdayMon(first));110 const end = addDays(last, 6 - weekdayMon(last));111 const out: string[] = [];112 for (let k = start; ; k = addDays(k, 1)) { out.push(k); if (k === end) break; }113 return out;114}115export function addMonths(key: string, n: number): string { const { y, m } = parseKey(key); const t = new Date(Date.UTC(y, m - 1 + n, 1)); return keyOf(t.getUTCFullYear(), t.getUTCMonth() + 1, 1); }116117/* ── Display ── */118const noon = (key: string) => { const { y, m, d } = parseKey(key); return new Date(Date.UTC(y, m - 1, d, 12)); };119export const fmtDayKey = (key: string, locale: string, opts: Intl.DateTimeFormatOptions) => new Intl.DateTimeFormat(locale, { ...opts, timeZone: 'UTC' }).format(noon(key));120export function fmtDateTime(iso: string | Date | null | undefined, tz: string, locale: string): string {121 if (!iso) return '—';122 const d = new Date(iso); if (Number.isNaN(d.getTime())) return String(iso);123 return new Intl.DateTimeFormat(locale, { timeZone: tz, dateStyle: 'medium', timeStyle: 'short' }).format(d) + ' ' + zoneAbbrev(d, tz, locale);124}125export function fmtDate(iso: string | Date | null | undefined, tz: string, locale: string): string {126 if (!iso) return '—';127 const d = new Date(iso); if (Number.isNaN(d.getTime())) return String(iso);128 return new Intl.DateTimeFormat(locale, { timeZone: tz, dateStyle: 'medium' }).format(d);129}130export const fmtTime = (iso: string | Date, tz: string, locale: string) => new Intl.DateTimeFormat(locale, { timeZone: tz, hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }).format(new Date(iso));131export function zoneAbbrev(instant: Date | string, tz: string, locale: string): string {132 const p = new Intl.DateTimeFormat(locale, { timeZone: tz, timeZoneName: 'short' }).formatToParts(new Date(instant)).find((x) => x.type === 'timeZoneName');133 return p?.value ?? tz;134}135136/** Date (`YYYY-MM-DD`) and time (`HH:MM`) typed in a zone → UTC instant. An ambiguous time resolves to its first occurrence; a non-existent one is an error. */137export function resolveLocal(date: string, time: string, tz: string): { utc: Date } | { error: 'incomplete' | 'gap' } {138 const d = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date); const h = /^(\d{2}):(\d{2})/.exec(time);139 if (!d || !h) return { error: 'incomplete' };140 const r = zonedToUtc({ y: Number(d[1]), m: Number(d[2]), d: Number(d[3]), h: Number(h[1]), mi: Number(h[2]) }, tz);141 return r.kind === 'ok' ? { utc: r.utc } : r.kind === 'overlap' ? { utc: r.first } : { error: 'gap' };142}143