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.

52 lines (50 loc) • 2.13 kB
import { Temporal } from "../../internal/temporal.js"; import { isOptionsArgument } from "../../internal/isObject.js"; import { optionOrDefault } from "../../internal/optionOrDefault.js"; import { isValidUtc } from "../validate/isValidUtc.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 = optionOrDefault(options?.inclusiveStart, true); const inclusiveEnd = optionOrDefault(options?.inclusiveEnd, true); if (!isValidUtc(value) || !isValidUtc(start) || !isValidUtc(end)) return false; let instant; let startInstant; let endInstant; try { instant = Temporal.Instant.from(value); startInstant = Temporal.Instant.from(start); endInstant = Temporal.Instant.from(end); } catch { 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 };