@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.
45 lines (43 loc) • 1.87 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { booleanOption } from "../../internal/typedOptions.js";
import { isObject, isOptionsArgument } from "../../internal/isObject.js";
import { utcInstantOf } from "../../internal/utcInstant.js";
// src/utc/validate/isValidUtcRange.ts
/**
* Return true if `value1` and `value2` form a valid UTC range — both parseable as
* ISO UTC datetime strings and the instant at `value1` is before the instant at `value2`.
*
* - Both inputs must be ISO 8601 UTC datetime strings (e.g. `"2024-01-01T10:00:00Z"`), as
* `isValidUtc` accepts, annotations included.
* - Leap-second strings return `false`.
* - Invalid input or malformed strings return `false`.
*
* @param props The two ends of the range, and whether equal ends are valid
* @returns boolean indicating whether the UTC range is valid
*
* @example isValidUtcRange({ value1: "2024-01-01T10:00:00Z", value2: "2024-12-31T23:59:59Z" }) // true
* @example isValidUtcRange({ value1: "2024-12-31T23:59:59Z", value2: "2024-01-01T10:00:00Z" }) // false
* @example isValidUtcRange({ value1: "2024-01-01T10:00:00Z", value2: "2024-01-01T10:00:00Z", options: { allowEqual: true } }) // true
*/
function isValidUtcRange(props) {
try {
if (!isObject(props)) return false;
const { value1, value2, options } = props;
if (!isOptionsArgument(options)) return false;
if (typeof value1 !== "string" || typeof value2 !== "string") return false;
const startInstant = utcInstantOf(value1);
if (startInstant === null) return false;
const endInstant = utcInstantOf(value2);
if (endInstant === null) return false;
try {
const cmp = Temporal.Instant.compare(startInstant, endInstant);
if (booleanOption(options?.allowEqual, false)) return cmp <= 0;
return cmp < 0;
} catch {
return false;
}
} catch {
return false;
}
}
export { isValidUtcRange };