@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.
42 lines (40 loc) • 1.84 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { isValidDate } from "./isValidDate.js";
import { isObject, isOptionsArgument } from "../../internal/isObject.js";
// src/plain/validate/isValidDateRange.ts
/**
* Return whether `value1` is before `value2`.
*
* - Validates both dates with `isValidDate`, so each endpoint's RFC 9557 annotations are read as
* `Temporal.PlainDate.from` reads them (an elective `[foo=bar]` or `[u-ca=iso8601]` is ignored).
* - Rejects leap seconds in either date.
*
* @param props The two values to compare and how equal values are treated
* @returns boolean indicating whether the date range is valid
*
* @example isValidDateRange({ value1: "2024-02-28", value2: "2024-02-29" }) // true
* @example isValidDateRange({ value1: "2024-02-29", value2: "2024-02-28" }) // false
* @example isValidDateRange({ value1: "2024-02-29", value2: "2024-02-29" }) // false
* @example isValidDateRange({ value1: "2024-02-29", value2: "2024-02-29", options: { allowEqual: true } }) // true
*/
function isValidDateRange(props) {
try {
if (!isObject(props)) return false;
const { value1, value2, options } = props;
if (!isOptionsArgument(options)) return false;
if (!isValidDate(value1) || !isValidDate(value2)) return false;
try {
const date1 = Temporal.PlainDate.from(value1);
const date2 = Temporal.PlainDate.from(value2);
const isLessThan = date1.year < date2.year || date1.year === date2.year && date1.month < date2.month || date1.year === date2.year && date1.month === date2.month && date1.day < date2.day;
const isEqual = date1.year === date2.year && date1.month === date2.month && date1.day === date2.day;
if (options?.allowEqual) return isLessThan || isEqual;
return isLessThan;
} catch {
return false;
}
} catch {
return false;
}
}
export { isValidDateRange };