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.27 kB
import { Temporal } from "../../internal/temporal.js"; import { booleanOption } from "../../internal/typedOptions.js"; import { plainTimeOf } from "../../internal/inputChecks.js"; import { isOptionsArgument } from "../../internal/isObject.js"; // src/plain/compare/isBetweenTime.ts /** * Return true when `time` is between `start` and `end` (inclusive by default). * * - Uses Temporal.PlainTime.compare to compare times. * - Returns false if start > end (invalid range). * - Returns false if any input is invalid. * - Note: PlainTime comparison does not account for day overflow. * * @param time ISO PlainTime string to check * @param start ISO PlainTime string for the start of the range * @param end ISO PlainTime string for the end of the range * @param options Whether each end of the range counts as inside it * @returns boolean indicating whether time is between start and end * * @example isBetweenTime("12:34:56", "12:00:00", "13:00:00") // true * @example isBetweenTime("12:34:56", "12:34:56", "13:00:00") // true * @example isBetweenTime("12:34:56", "12:34:57", "13:00:00") // false * @example isBetweenTime("12:34:56", "12:00:00", "12:34:56") // true * @example isBetweenTime("12:34:56", "12:00:00", "12:34:55") // false * @example isBetweenTime("invalid", "12:00:00", "13:00:00") // false * @example isBetweenTime("12:34:56", "invalid", "13:00:00") // false * @example isBetweenTime("12:34:56", "12:00:00", "invalid") // false */ function isBetweenTime(time, start, end, options) { try { if (!isOptionsArgument(options)) return false; const inclusiveStart = booleanOption(options?.inclusiveStart, true); const inclusiveEnd = booleanOption(options?.inclusiveEnd, true); const t = plainTimeOf(time); const s = plainTimeOf(start); const e = plainTimeOf(end); if (t === null || s === null || e === null) return false; try { if (Temporal.PlainTime.compare(s, e) === 1) return false; const startCheck = inclusiveStart ? Temporal.PlainTime.compare(s, t) <= 0 : Temporal.PlainTime.compare(s, t) < 0; const endCheck = inclusiveEnd ? Temporal.PlainTime.compare(t, e) <= 0 : Temporal.PlainTime.compare(t, e) < 0; return startCheck && endCheck; } catch { return false; } } catch { return false; } } export { isBetweenTime };