@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.
39 lines (37 loc) • 2.22 kB
JavaScript
import { parseInstantNanoseconds } from "../../internal/instantNanoseconds.js";
import { parseIntervalNanoseconds } from "../../internal/intervalNanoseconds.js";
// src/interval/compare/intervalContains.ts
/**
* Return true when an ISO 8601 instant string lies inside a half-open interval.
*
* - `start ≤ t < end`: `start` is inside, `end` is not.
* - Always `false` for an empty interval (`start === end`) — it contains no instant.
* - Compares instants: `isoString` may name a different zone from either endpoint.
* - The positional `intervalContainsUtc`, `intervalContainsZoned` (…) follow the same half-open
* rule and exclude `end`.
* - Returns `false` on invalid input — `interval` not an `Interval`, or `isoString` not an
* instant string (offset required, no leap second, no unknown critical annotation such as
* `[!foo=bar]`). Zone, calendar and elective annotations are ignored, as
* `Temporal.Instant.from` ignores them.
*
* @param interval `{ start, end }` record of ISO 8601 instant strings
* @param isoString ISO 8601 instant string to test
* @returns true if the instant is inside the interval, or false on invalid input
*
* @example intervalContains({ start: "2024-01-01T09:00:00Z", end: "2024-01-01T17:00:00Z" }, "2024-01-01T09:00:00Z") // true — start is inside
* @example intervalContains({ start: "2024-01-01T09:00:00Z", end: "2024-01-01T17:00:00Z" }, "2024-01-01T17:00:00Z") // false — end is not
* @example intervalContains({ start: "2024-01-01T09:00:00Z", end: "2024-01-01T17:00:00Z" }, "2024-01-01T04:00:00-05:00") // true — same instant as start
* @example intervalContains({ start: "2024-01-01T12:00:00Z", end: "2024-01-01T12:00:00Z" }, "2024-01-01T12:00:00Z") // false — empty interval
* @example intervalContains({ start: "2024-01-01T09:00:00Z", end: "2024-01-01T17:00:00Z" }, "2024-01-01T12:00:00") // false — no offset
*/
function intervalContains(interval, isoString) {
try {
const record = parseIntervalNanoseconds(interval);
const instant = parseInstantNanoseconds(isoString);
if (record === null || instant === null) return false;
return record.start <= instant && instant < record.end;
} catch {
return false;
}
}
export { intervalContains };