@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.
43 lines (41 loc) • 1.8 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { booleanOption } from "../../internal/typedOptions.js";
import { plainDateTimeOf } from "../../internal/inputChecks.js";
import { isObject, isOptionsArgument } from "../../internal/isObject.js";
// src/plain/validate/isValidDateTimeRange.ts
/**
* Return true if `value1` and `value2` form a valid datetime range — both parseable as
* ISO PlainDateTime strings and `value1` before `value2`.
*
* - Both inputs must be ISO 8601 datetime strings (e.g. `"2024-01-01T10:00:00"`), as
* `isValidDateTime` accepts, annotations included.
* - Invalid input, malformed strings, or leap-second strings return `false`.
*
* @param props The two values to compare and how equal values are treated
* @returns boolean indicating whether the datetime range is valid
*
* @example isValidDateTimeRange({ value1: "2024-01-01T10:00:00", value2: "2024-12-31T23:59:59" }) // true
* @example isValidDateTimeRange({ value1: "2024-12-31T23:59:59", value2: "2024-01-01T10:00:00" }) // false
* @example isValidDateTimeRange({ value1: "2024-01-01T10:00:00", value2: "2024-01-01T10:00:00", options: { allowEqual: true } }) // true
*/
function isValidDateTimeRange(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 dt1 = plainDateTimeOf(value1);
const dt2 = plainDateTimeOf(value2);
if (dt1 === null || dt2 === null) return false;
try {
const cmp = Temporal.PlainDateTime.compare(dt1, dt2);
if (booleanOption(options?.allowEqual, false)) return cmp <= 0;
return cmp < 0;
} catch {
return false;
}
} catch {
return false;
}
}
export { isValidDateTimeRange };