@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.
132 lines (130 loc) • 6.98 kB
JavaScript
import { Temporal } from "./temporal.js";
import { EXTENDED_UTC_OFFSET, hasZonedInstantShape } from "./isoStringBody.js";
import { utcOffsetStringNanoseconds, zonedDateTimeOf } from "./zonedWallClock.js";
import { parseInstantNanoseconds } from "./instantNanoseconds.js";
import { wallClockAtOffset } from "./wallClockAtOffset.js";
// src/internal/exactMoment.ts
/**
* Trailing `Z` or extended offset of an instant string. The offset grammar
* is `isValidInstant`'s own (`EXTENDED_UTC_OFFSET`), so every offset it accepts, `,` fractions
* included, is captured as written.
*/
const trailingOffset = new RegExp(`(Z|${EXTENDED_UTC_OFFSET})$`);
/**
* Read an exact moment the way `transitTime` reads a departure, or `null`.
*
* - A zoned string (`…+09:00[Asia/Tokyo]`) is read through its bracket, which must name a
* real zone that agrees with the offset, as `isValidZonedDateTime` requires. An offset written
* to the minute agrees when it is the zone's sub-minute offset rounded (TC39
* `ToTemporalZonedDateTime`, match-minutes), which is how `writeExactMoment` writes one.
* - A wall time with a bracket and no offset is read in that zone with the `"compatible"`
* disambiguation policy (`context/reference/LOCAL_TIME_RESOLUTION.md`): an **ambiguous** wall
* time, a fall-back hour the clock ran through twice, resolves to the **earlier** instant
* (`2024-10-27T01:30:00[Europe/London]` is `01:30+01:00`), and a **nonexistent** one, a
* spring-forward hour the clock skipped, to the **later** instant
* (`2024-03-31T01:30:00[Europe/London]` is `02:30+01:00`). A caller that must not guess
* refuses the offset-less form before calling, as `nextDeparture` does.
* - A string that names a zone the zoned read rejects is `null`; it never falls back to its
* offset. That includes a zoned string whose local date is −271821-04-19, which
* `Temporal.ZonedDateTime.from` refuses although its instant is in range.
* - Otherwise an instant (`Z` or an offset) as `parseInstantNanoseconds` reads it, with no
* annotation of any kind (a bracket that is not a valid zoned string is `null`). Its offset text
* is kept exactly as written, sub-minute and `,` fractions included.
*
* @param value candidate zoned datetime or instant string
* @returns the moment's epoch nanoseconds and notation, or null on invalid input
*
* @example readExactMoment("2024-06-15T10:00:00+09:00") // { nanoseconds: 1718413200000000000n, notation: { kind: "offset", offset: "+09:00" } }
* @example readExactMoment("2024-06-15T10:00:00Z[Not/AZone]") // null
* @example readExactMoment("2024-03-31T01:30:00[Europe/London]") // { nanoseconds: 1711848600000000000n, notation: { kind: "zone", timeZone: "Europe/London" } } (nonexistent: the later instant, 02:30+01:00)
*/
function readExactMoment(value) {
if (typeof value !== "string") return null;
try {
const zoned = zonedDateTimeOf(value);
if (zoned !== null) return {
nanoseconds: zoned.epochNanoseconds,
notation: {
kind: "zone",
timeZone: zoned.timeZoneId
}
};
const nanoseconds = parseInstantNanoseconds(value);
if (nanoseconds === null) return null;
const offset = trailingOffset.exec(value)?.[1] ?? "Z";
return {
nanoseconds,
notation: offset === "Z" ? { kind: "utc" } : {
kind: "offset",
offset
}
};
} catch {
return null;
}
}
/**
* Read the instant of a zoned string that writes its offset: exactly the shape `cutoffAt`
* writes, `<date>T<time>±HH:MM[Zone]` (an offset or `Z`, then one time zone bracket, the
* critical `[!Zone]` included, and nothing after it).
*
* - The bracket must name a real zone that agrees with the offset, as `readExactMoment` reads
* it. A bracket that is itself an offset (`[+02:00]`) is a time zone to GMT
* (`isValidTimeZone("+02:00")`) and is read; `cutoffAt` writes it for an offset `timeZone`.
* - A bare instant (`Z` or an offset with no bracket) is a different kind and is `null`, as is
* a wall time with no offset (it names no moment) and any other annotation.
*
* @param value candidate zoned datetime string
* @returns the moment's instant, or null on invalid input
*
* @example zonedInstantOf("2024-06-12T17:00:00+02:00[Europe/Amsterdam]")?.toString() // "2024-06-12T15:00:00Z"
* @example zonedInstantOf("2024-06-12T17:00:00+02:00[!Europe/Amsterdam]")?.toString() // "2024-06-12T15:00:00Z"
* @example zonedInstantOf("2024-06-12T17:00:00+02:00") // null
* @example zonedInstantOf("2024-06-12T17:00:00+02:00[+02:00]")?.toString() // "2024-06-12T15:00:00Z"
* @example zonedInstantOf("2024-06-12T17:00:00[Europe/Amsterdam]") // null
*/
function zonedInstantOf(value) {
if (typeof value !== "string" || !hasZonedInstantShape(value)) return null;
try {
const zoned = zonedDateTimeOf(value);
if (zoned === null) return null;
return zoned.toInstant();
} catch {
return null;
}
}
/**
* Write epoch nanoseconds the way a moment was written: in its zone, at its offset text, or as a
* `Z` instant. `""` when the nanoseconds leave the instant range (±8.64e21 ns).
*
* - A zone notation is written as Temporal writes a `ZonedDateTime`: the offset in force at that
* instant, rounded to the minute (`-00:45` for Monrovia's −00:44:30), then the bracket.
* `readExactMoment` and `parseInstantNanoseconds` read that string back as the same instant,
* with two exceptions, both Temporal's own. A wall time repeated inside a sub-minute offset
* change reads as its first pass, in both readers (`parseInstantNanoseconds` states the
* rule). And `readExactMoment`, a zoned read, refuses a string whose local date is
* −271821-04-19 (`CheckISODaysRange` in `Temporal.ZonedDateTime.from`): the string written
* for the first hours of the instant range in a zone west of Greenwich reads as `null` there,
* and as its instant in `parseInstantNanoseconds`
* (`context/domination/js-temporal-polyfill-bugs.md` § J).
* - An offset notation keeps its text as written. The wall clock is shifted, never the instant
* (`wallClockAtOffset`), so the last hours of the range still write at a positive offset.
*
* @param nanoseconds epoch nanoseconds of the moment to write
* @param notation how to write it, from `readExactMoment`
* @returns the moment as a zoned, offset or `Z` string, or "" when it is out of range
*
* @example writeExactMoment(0n, { kind: "offset", offset: "+09:00" }) // "1970-01-01T09:00:00+09:00"
* @example writeExactMoment(0n, { kind: "zone", timeZone: "UTC" }) // "1970-01-01T00:00:00+00:00[UTC]"
*/
function writeExactMoment(nanoseconds, notation) {
try {
const instant = Temporal.Instant.fromEpochNanoseconds(nanoseconds);
if (notation.kind === "zone") return instant.toZonedDateTimeISO(notation.timeZone).toString();
if (notation.kind === "utc") return instant.toString();
return `${wallClockAtOffset(instant, utcOffsetStringNanoseconds(notation.offset)).toString()}${notation.offset}`;
} catch {
return "";
}
}
export { readExactMoment, writeExactMoment, zonedInstantOf };