UNPKG

@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.

42 lines (40 loc) • 2.32 kB
import { Temporal } from "../../../internal/temporal.js"; import { zonedDateTimeOf } from "../../../internal/zonedWallClock.js"; // src/zoned/interval/validate/isValidZonedInterval.ts /** * Return true if `start` and `end` form a valid zoned interval — both valid ISO ZonedDateTime * strings (`isValidZonedDateTime`) and the instant at `start` is <= the instant at `end`. * * - Both inputs must be valid ISO 8601 zoned datetime strings. * - Equal `start === end` is valid. * - Comparison is done by instant, so intervals spanning DST transitions are compared * by absolute time. * - Reads each endpoint as `isValidZonedDateTime` does: the zone bracket is the only annotation, * and a calendar (`[u-ca=iso8601]`, `[u-ca=hebrew]`) or an elective one (`[foo=bar]`) returns * `false`. `isValidCalendarZonedInterval` reads the calendar. * - Invalid input, malformed strings, or leap-second strings return `false`. * * @param start ISO ZonedDateTime string (interval start) * @param end ISO ZonedDateTime string (interval end) * @returns true if start and end form a valid zoned interval, or false on invalid input * * @example isValidZonedInterval("2024-01-01T10:00:00+00:00[UTC]", "2024-12-31T23:59:59+00:00[UTC]") // true * @example isValidZonedInterval("2024-06-15T12:00:00+02:00[Africa/Johannesburg]", "2024-06-15T12:00:00+02:00[Africa/Johannesburg]") // true * @example isValidZonedInterval("2024-12-31T23:59:59+00:00[UTC]", "2024-01-01T10:00:00+00:00[UTC]") // false * @example isValidZonedInterval("2024-01-01T10:00:00+00:00[UTC][u-ca=iso8601]", "2024-12-31T23:59:59+00:00[UTC][foo=bar]") // false (only the zone bracket is accepted) * @example isValidZonedInterval("2024-01-01T10:00:00+00:00[UTC][u-ca=hebrew]", "2024-12-31T23:59:59+00:00[UTC]") // false (a calendar: use isValidCalendarZonedInterval) * @example isValidZonedInterval("invalid", "2024-12-31T23:59:59+00:00[UTC]") // false */ function isValidZonedInterval(start, end) { const startZoned = zonedDateTimeOf(start); const endZoned = zonedDateTimeOf(end); if (startZoned === null || endZoned === null) return false; try { const startInstant = startZoned.toInstant(); const endInstant = endZoned.toInstant(); return Temporal.Instant.compare(startInstant, endInstant) <= 0; } catch { return false; } } export { isValidZonedInterval };