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.

55 lines (53 loc) • 2.38 kB
import { Temporal } from "../../internal/temporal.js"; import { isOptionsArgument } from "../../internal/isObject.js"; import { optionOrDefault } from "../../internal/optionOrDefault.js"; import { zonedDateTimeFrom } from "../../internal/zonedWallClock.js"; import { isValidZonedDateTime } from "../validate/isValidZonedDateTime.js"; // src/zoned/compare/isBetweenZoned.ts /** * Return true when `zoned` is between `start` and `end` (inclusive by default). * * - Validates inputs and then compares using Temporal.Instant (same instant semantics). * - Returns false for invalid inputs. * * @param zoned ISO ZonedDateTime string to check * @param start ISO ZonedDateTime string for the start of the range * @param end ISO ZonedDateTime string for the end of the range * @param options optional settings for whether each end of the range is included * @returns boolean indicating whether zoned is between start and end * * @example isBetweenZoned("2024-02-29T12:00:00+00:00[UTC]", "2024-02-29T11:00:00+00:00[UTC]", "2024-02-29T13:00:00+00:00[UTC]") // true * @example isBetweenZoned("invalid", "2024-02-29T11:00:00+00:00[UTC]", "2024-02-29T13:00:00+00:00[UTC]") // false */ function isBetweenZoned(zoned, start, end, options) { try { if (!isOptionsArgument(options)) return false; const inclusiveStart = optionOrDefault(options?.inclusiveStart, true); const inclusiveEnd = optionOrDefault(options?.inclusiveEnd, true); if (!isValidZonedDateTime(zoned) || !isValidZonedDateTime(start) || !isValidZonedDateTime(end)) return false; let zdt; let startZdt; let endZdt; try { zdt = zonedDateTimeFrom(zoned); startZdt = zonedDateTimeFrom(start); endZdt = zonedDateTimeFrom(end); } catch { return false; } try { const startInstant = startZdt.toInstant(); const endInstant = endZdt.toInstant(); const zonedInstant = zdt.toInstant(); if (Temporal.Instant.compare(startInstant, endInstant) === 1) return false; const startCheck = inclusiveStart ? Temporal.Instant.compare(startInstant, zonedInstant) <= 0 : Temporal.Instant.compare(startInstant, zonedInstant) < 0; const endCheck = inclusiveEnd ? Temporal.Instant.compare(zonedInstant, endInstant) <= 0 : Temporal.Instant.compare(zonedInstant, endInstant) < 0; return startCheck && endCheck; } catch { return false; } } catch { return false; } } export { isBetweenZoned };