Files
Rosea/packages/engine/src/time/localDay.ts
T

101 lines
4.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* The ONLY place in the repository where a day is computed (CLAUDE.md §7).
*
* A day is always local to a named IANA time zone, and the zone is always a
* parameter. The engine never asks the device which zone it is in: the app
* passes the zone of the city the player chose, or the device's own zone as the
* fallback (CLAUDE.md §4 `profile`).
*
* Never `toISOString().slice(0, 10)`: that is the UTC day, and in Prague it
* records Monday-evening care as Tuesday's.
*/
/** A calendar day, `YYYY-MM-DD`, in some player's local time. */
export type LocalDay = string;
const LOCAL_DAY = /^\d{4}-\d{2}-\d{2}$/;
// Memoised per zone. Constructing a DateTimeFormat costs far more than using one.
// This is a cache of a pure function's machinery, not state: the output depends
// only on the arguments.
const formatters = new Map<string, Intl.DateTimeFormat>();
function formatterFor(timeZone: string): Intl.DateTimeFormat {
let formatter = formatters.get(timeZone);
if (formatter === undefined) {
// Throws RangeError for an unknown zone, which is the right failure: a
// mistyped zone silently falling back to UTC is the bug this module exists
// to prevent.
formatter = new Intl.DateTimeFormat('en-CA', {
timeZone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
calendar: 'iso8601',
numberingSystem: 'latn'
});
formatters.set(timeZone, formatter);
}
return formatter;
}
/** The local calendar day of `epochMs` in `timeZone`. */
export function localDay(epochMs: number, timeZone: string): LocalDay {
if (!Number.isFinite(epochMs)) {
throw new RangeError(`localDay: epochMs must be a finite number, got ${String(epochMs)}`);
}
const parts = formatterFor(timeZone).formatToParts(epochMs);
const part = (type: Intl.DateTimeFormatPartTypes): string => {
const value = parts.find((p) => p.type === type)?.value;
if (value === undefined) throw new RangeError(`localDay: no ${type} for ${epochMs} in ${timeZone}`);
return value;
};
const day = `${part('year')}-${part('month')}-${part('day')}`;
if (!LOCAL_DAY.test(day)) {
// Years before 1000 or after 9999 would not be four digits. No player tends
// a rose then; refusing is better than writing an ambiguous day to the log.
throw new RangeError(`localDay: ${epochMs} gives an unrepresentable day '${day}'`);
}
return day;
}
const clockFormatters = new Map<string, Intl.DateTimeFormat>();
/** Minutes after local midnight on the clock of `timeZone` (0–1439): what a clock there shows. */
export function localMinutes(epochMs: number, timeZone: string): number {
if (!Number.isFinite(epochMs)) throw new RangeError(`localMinutes: epochMs must be a finite number, got ${String(epochMs)}`);
let f = clockFormatters.get(timeZone);
if (f === undefined) {
f = new Intl.DateTimeFormat('en-GB', { timeZone, hour: '2-digit', minute: '2-digit', hourCycle: 'h23', numberingSystem: 'latn' });
clockFormatters.set(timeZone, f);
}
const parts = f.formatToParts(epochMs);
const n = (type: Intl.DateTimeFormatPartTypes): number => Number(parts.find((p) => p.type === type)?.value);
return n('hour') * 60 + n('minute');
}
/** Whole calendar days from `from` to `to`: positive when `to` is later. */
export function daysBetween(from: LocalDay, to: LocalDay): number {
const utc = (day: LocalDay): number => {
if (!isLocalDay(day)) throw new RangeError(`daysBetween: '${day}' is not a LocalDay`);
const [y, m, d] = day.split('-').map(Number) as [number, number, number];
return Date.UTC(y, m - 1, d);
};
return Math.round((utc(to) - utc(from)) / 86_400_000);
}
/** The calendar day `days` after `day` (before, if negative). A calendar step: no zone, no DST. */
export function addDays(day: LocalDay, days: number): LocalDay {
if (!isLocalDay(day)) throw new RangeError(`addDays: '${day}' is not a LocalDay`);
if (!Number.isInteger(days)) throw new RangeError(`addDays: ${days} is not a whole number of days`);
const [y, m, d] = day.split('-').map(Number) as [number, number, number];
return localDay(Date.UTC(y, m - 1, d + days), 'UTC');
}
/** Whether `value` has the shape of a LocalDay. Does not check that the date exists. */
export function isLocalDay(value: string): value is LocalDay {
return LOCAL_DAY.test(value);
}