src/tz.js
// Time-zone and calendar-date helpers built only on Intl and Date (no bundled tz database: the
// IANA rules come from the ICU data shipped with Node.js). All instants are epoch milliseconds.
const dtfCache = new Map();
function formatter(tz) {
let f = dtfCache.get(tz);
if (!f) {
f = new Intl.DateTimeFormat("en-US", {
timeZone: tz,
hourCycle: "h23",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
});
dtfCache.set(tz, f);
}
return f;
}
export function isValidTimeZone(tz) {
if (typeof tz !== "string" || tz.length === 0 || tz.length > 64) return false;
try {
formatter(tz);
return true;
} catch {
return false;
}
}
/** Wall-clock fields of an instant in a time zone. */
export function utcToZoned(ms, tz) {
const parts = formatter(tz).formatToParts(new Date(ms));
const get = (type) => Number(parts.find((p) => p.type === type)?.value);
let hh = get("hour");
if (hh === 24) hh = 0; // defensive: some older ICU builds print midnight as 24
return { y: get("year"), m: get("month"), d: get("day"), hh, mi: get("minute"), ss: get("second") };
}
/** UTC offset (local minus UTC, in ms) in effect at an instant. */
export function offsetMs(ms, tz) {
if (tz === "UTC") return 0;
const z = utcToZoned(ms, tz);
const asUtc = Date.UTC(z.y, z.m - 1, z.d, z.hh, z.mi, z.ss);
return asUtc - Math.floor(ms / 1000) * 1000;
}
/**
* Converts a wall-clock time in `tz` to an instant.
* - Ambiguous local times (DST fall-back) resolve to the FIRST occurrence (RFC 5545 \u00a73.3.5).
* - Non-existent local times (DST spring-forward gap) use the offset in effect before the gap,
* so 02:30 on a US spring-forward day becomes 03:30 daylight time (RFC 5545 \u00a73.3.5).
*/
export function zonedToUtc(y, m, d, hh, mi, ss, tz) {
const t = Date.UTC(y, m - 1, d, hh, mi, ss);
if (tz === "UTC") return t;
const before = offsetMs(t - 86400000, tz);
const after = offsetMs(t + 86400000, tz);
const candidates = [...new Set([t - before, t - after])].filter((c) => offsetMs(c, tz) === t - c);
if (candidates.length > 0) return Math.min(...candidates);
return t - before;
}
// Calendar day numbers: days since 1970-01-01 for a local calendar date (time-zone independent).
export const dayNum = (y, m, d) => Math.floor(Date.UTC(y, m - 1, d) / 86400000);
export function fromDayNum(n) {
const dt = new Date(n * 86400000);
return { y: dt.getUTCFullYear(), m: dt.getUTCMonth() + 1, d: dt.getUTCDate() };
}
/** 0 = Sunday ... 6 = Saturday */
export const weekday = (n) => (((n % 7) + 7 + 4) % 7);
export const daysInMonth = (y, m) => new Date(Date.UTC(y, m, 0)).getUTCDate();
export function ymd(n) {
const { y, m, d } = fromDayNum(n);
return `${String(y).padStart(4, "0")}-${String(m).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
}
export function parseYmd(s) {
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(s));
if (!m) return null;
const y = Number(m[1]);
const mo = Number(m[2]);
const d = Number(m[3]);
if (mo < 1 || mo > 12 || d < 1 || d > daysInMonth(y, mo)) return null;
return dayNum(y, mo, d);
}
/** ISO 8601 UTC string without a zero milliseconds suffix. */
export function isoUtc(ms) {
return new Date(ms).toISOString().replace(".000Z", "Z");
}
/** ISO 8601 local time with numeric offset, e.g. 2026-03-09T09:00-04:00. */
export function isoLocal(ms, tz) {
const z = utcToZoned(ms, tz);
const off = Math.round(offsetMs(ms, tz) / 60000);
const sign = off < 0 ? "-" : "+";
const abs = Math.abs(off);
const p = (n) => String(n).padStart(2, "0");
return `${z.y}-${p(z.m)}-${p(z.d)}T${p(z.hh)}:${p(z.mi)}${sign}${p(Math.floor(abs / 60))}:${p(abs % 60)}`;
}
/**
* Parses either an ISO date-time with Z/offset, or a local "YYYY-MM-DDTHH:MM[:SS]" interpreted in `tz`.
* Returns epoch ms or null.
*/
export function parseInstant(s, tz) {
const str = String(s).trim();
const local = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2}))?$/.exec(str);
if (local) {
if (!tz) return null;
const [, y, mo, d, hh, mi, ss] = local.map(Number);
if (mo < 1 || mo > 12 || d < 1 || d > daysInMonth(y, mo) || hh > 23 || mi > 59) return null;
return zonedToUtc(y, mo, d, hh, mi, Number.isNaN(ss) ? 0 : ss, tz);
}
if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/i.test(str)) return null;
const ms = Date.parse(str);
return Number.isNaN(ms) ? null : ms;
}