@northguild/gmt
Version:
Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.
84 lines (82 loc) • 4.73 kB
JavaScript
import { canonicalCalendarSystem, computationCalendarId } from "./calendarSystemIds.js";
import { hasCalendarZonedShape } from "./isoStringBody.js";
import { hasSecond60Field } from "./inputChecks.js";
import { zonedDateTimeFrom } from "./zonedWallClock.js";
// src/internal/calendarZonedString.ts
/**
* Parse a GMT ZonedDateTime string into a Temporal.ZonedDateTime, read exactly as
* `Temporal.ZonedDateTime.from` reads it (`"2024-02-24T14:30:00+02:00[Asia/Jerusalem][u-ca=hebrew]"`,
* which is what `Temporal.ZonedDateTime#toString()` writes). Throws on invalid input — callers wrap
* this in try-catch per GMT's sentinel contract.
*
* - The whole string must be GMT's strict ISO 8601 extended shape (`hasCalendarZonedShape`:
* `<date>T<time>`, then nothing, `Z` or `±HH:MM[:SS[.fraction]]`, then the time zone annotation,
* then at most one calendar annotation `[u-ca=<id>]` or `[!u-ca=<id>]`) and nothing else, as
* `isValidCalendarZonedDateTime` requires. Basic format, a space or lower-case `t` separator, a
* lower-case `z`, an hour-only time or offset, a date without a time, an elective annotation
* (`[foo=bar]`), an unknown critical annotation, a second `u-ca` and a calendar before the zone
* all throw, although `Temporal.ZonedDateTime.from` reads some of them.
* - The digits are ISO. The whole string goes to `zonedDateTimeFrom` (`Temporal.ZonedDateTime.from`,
* correct at the range limits), which validates the date, time, offset, zone and calendar.
* - The calendar id is Temporal's canonical one (`CanonicalizeCalendar`) and must be a
* `CalendarSystem`.
* - The result computes in `computationCalendarId(calendar)` (`"ethioaa"` for `"ethiopic"` and
* `"coptic"`), so callers that write a string back take the calendar from
* `calendarSystemOfZonedValue(value)`.
* - `hasSecond60Field` runs first: `Temporal.ZonedDateTime.from("2024-06-30T23:59:60+00:00[UTC]")`
* clamps to `:59` instead of throwing.
*
* @param value ISO zoned datetime string, optionally with one calendar annotation after the zone
* @param options optional Temporal `disambiguation`/`offset`, passed through to
* `Temporal.ZonedDateTime.from` so a caller's own DST/offset policy still applies
* @returns Temporal.ZonedDateTime in the computation calendar (`iso8601` when unannotated)
*/
function parseCalendarZonedValue(value, options) {
if (hasSecond60Field(value)) throw new RangeError(`Leap seconds are not supported: ${value}`);
if (!hasCalendarZonedShape(value)) throw new RangeError(`Not an extended ISO 8601 zoned date-time: ${String(value)}`);
const zoned = zonedDateTimeFrom(value, options);
if (zoned.timeZoneId.length === 0) throw new RangeError(`Missing time zone: ${value}`);
const calendar = canonicalCalendarSystem(zoned.calendarId);
if (!calendar) throw new RangeError(`Unsupported calendar: ${zoned.calendarId}`);
return zoned.withCalendar(computationCalendarId(calendar));
}
/**
* The check behind `isValidCalendarZonedDateTime`: the `ZonedDateTime` `parseCalendarZonedValue`
* reads, or `null` where it throws.
*
* @param value the candidate; a value that is not a non-empty string is not a zoned date-time
* @returns the `ZonedDateTime` in the computation calendar, else `null`
*
* @example calendarZonedOf("2024-02-24T14:30:00+02:00[Asia/Jerusalem][u-ca=hebrew]")?.calendarId // "hebrew"
* @example calendarZonedOf("2024-02-24T14:30:00") // null
* @example calendarZonedOf(null) // null
*/
function calendarZonedOf(value) {
if (typeof value !== "string" || value.length === 0) return null;
try {
const zoned = parseCalendarZonedValue(value);
return zoned.timeZoneId.length > 0 ? zoned : null;
} catch {
return null;
}
}
/**
* Write a Temporal.ZonedDateTime as a GMT ZonedDateTime string in `calendar`: exactly
* `Temporal.ZonedDateTime#toString()` for that instant, zone and calendar — the ISO date and time,
* the offset, `[<timeZone>]`, then `[u-ca=<id>]` for every calendar but `"iso8601"`
* (`FormatCalendarAnnotation` with `"auto"`).
*
* The calendar is passed in rather than read from `zdt.calendarId`: `"ethiopic"` and `"coptic"`
* compute in `"ethioaa"`, and boundary points synthesized with
* `Temporal.Instant.prototype.toZonedDateTimeISO` are `iso8601`. The instant, wall time and zone
* are written as they are; only the annotation names the calendar.
*
* @param zdt Temporal.ZonedDateTime to write, in any calendar
* @param calendar the CalendarSystem the string names
* @returns the RFC 9557 zoned datetime string
*/
function formatZonedInCalendar(zdt, calendar) {
const iso = zdt.withCalendar("iso8601").toString();
return calendar === "iso8601" ? iso : `${iso}[u-ca=${calendar}]`;
}
export { calendarZonedOf, formatZonedInCalendar, parseCalendarZonedValue };