Project Files
src / timezone / timezone.ts
/**
* Timezone resolution helpers built on the host ICU database.
*/
import { InvalidTimezoneError } from "../errors/invalid-timezone-error"
/**
* Validate that the supplied timezone name is recognised by the host ICU database.
*
* @param timezone - The IANA timezone name to validate.
* @throws When the name is not a recognised IANA timezone.
*/
export function validateTimezone(timezone: string): void {
try {
new Intl.DateTimeFormat("en-US", { timeZone: timezone })
} catch {
throw new InvalidTimezoneError(timezone)
}
}
/**
* Resolve the host system's IANA timezone name as reported by the ICU runtime.
*
* @returns The host timezone (e.g. `Europe/London`), or `UTC` if the runtime does not report one.
*/
export function resolveHostTimezone(): string {
const { timeZone } = Intl.DateTimeFormat().resolvedOptions()
return timeZone === "" ? "UTC" : timeZone
}
/**
* Format a date in the requested timezone using `en-CA` to produce ISO-style `YYYY-MM-DD HH:mm:ss`.
*
* @param date - The instant to format.
* @param timezone - The IANA timezone in which to render the instant.
* @returns The formatted local date-time string.
*/
export function formatInTimezone(date: Date, timezone: string): string {
const formatter = new Intl.DateTimeFormat("en-CA", {
timeZone: timezone,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
})
return formatter.format(date).replace(", ", " ")
}