@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.81 kB
JavaScript
import { booleanOption } from "../../internal/typedOptions.js";
import { plainDateOf } from "../../internal/inputChecks.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 an annotation of any kind on either endpoint
* (`[foo=bar]`, `[u-ca=iso8601]`, a time zone) returns `false`.
* - 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;
const date1 = plainDateOf(value1);
const date2 = plainDateOf(value2);
if (date1 === null || date2 === null) return false;
try {
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 (booleanOption(options?.allowEqual, false)) return isLessThan || isEqual;
return isLessThan;
} catch {
return false;
}
} catch {
return false;
}
}
export { isValidDateRange };