@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.18 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { booleanOption } from "../../internal/typedOptions.js";
import { zonedDateTimeOf } from "../../internal/zonedWallClock.js";
import { isOptionsArgument } from "../../internal/isObject.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 = booleanOption(options?.inclusiveStart, true);
const inclusiveEnd = booleanOption(options?.inclusiveEnd, true);
const zdt = zonedDateTimeOf(zoned);
const startZdt = zonedDateTimeOf(start);
const endZdt = zonedDateTimeOf(end);
if (zdt === null || startZdt === null || endZdt === null) 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 };