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.

47 lines (45 loc) • 2.06 kB
import { Temporal } from "../../internal/temporal.js"; import { booleanOption } from "../../internal/typedOptions.js"; import { isOptionsArgument } from "../../internal/isObject.js"; import { utcInstantOf } from "../../internal/utcInstant.js"; // src/utc/calculate/isBetweenUtc.ts /** * Return true when `value` is between `start` and `end` (inclusive by default). * * - Uses Temporal.Instant.compare for comparison. * - Returns false if start > end or inputs are invalid. * * @param value ISO UTC datetime string to check * @param start ISO UTC datetime string for range start * @param end ISO UTC datetime string for range end * @param options Whether each boundary counts as inside the range * @returns boolean indicating whether value is between start and end * * @example isBetweenUtc("2024-03-15T12:00:00Z", "2024-03-10T12:00:00Z", "2024-03-20T12:00:00Z") // true * @example isBetweenUtc("2024-03-25T12:00:00Z", "2024-03-10T12:00:00Z", "2024-03-20T12:00:00Z") // false * @example isBetweenUtc("invalid", "2024-03-10T12:00:00Z", "2024-03-20T12:00:00Z") // false */ function isBetweenUtc(value, start, end, options) { try { if (!isOptionsArgument(options)) return false; const inclusiveStart = booleanOption(options?.inclusiveStart, true); const inclusiveEnd = booleanOption(options?.inclusiveEnd, true); const instant = utcInstantOf(value); if (instant === null) return false; const startInstant = utcInstantOf(start); if (startInstant === null) return false; const endInstant = utcInstantOf(end); if (endInstant === null) return false; try { if (Temporal.Instant.compare(startInstant, endInstant) === 1) return false; const startCheck = inclusiveStart ? Temporal.Instant.compare(startInstant, instant) <= 0 : Temporal.Instant.compare(startInstant, instant) < 0; const endCheck = inclusiveEnd ? Temporal.Instant.compare(instant, endInstant) <= 0 : Temporal.Instant.compare(instant, endInstant) < 0; return startCheck && endCheck; } catch { return false; } } catch { return false; } } export { isBetweenUtc };