@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.
50 lines (48 loc) • 2.17 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { booleanOption } from "../../internal/typedOptions.js";
import { plainDateOf } from "../../internal/inputChecks.js";
import { isOptionsArgument } from "../../internal/isObject.js";
// src/plain/compare/isBetweenDate.ts
/**
* Return true when `date` is between `start` and `end` (inclusive by default).
*
* - Uses Temporal.PlainDate.compare to compare dates.
* - Returns false if start > end (invalid range).
* - Returns false if any input is invalid.
*
* @param date ISO PlainDate string to check
* @param start ISO PlainDate string for the start of the range
* @param end ISO PlainDate string for the end of the range
* @param options Whether each end of the range counts as inside it
* @returns boolean indicating whether date is between start and end
*
* @example isBetweenDate("2024-02-29", "2024-02-01", "2024-02-28") // false
* @example isBetweenDate("2024-02-29", "2024-02-01", "2024-02-29") // true
* @example isBetweenDate("2024-02-29", "2024-02-29", "2024-02-28") // false
* @example isBetweenDate("2024-02-29", "2024-02-28", "2024-03-01") // true
* @example isBetweenDate("invalid", "2024-02-01", "2024-02-28") // false
* @example isBetweenDate("2024-02-29", "invalid", "2024-02-28") // false
* @example isBetweenDate("2024-02-29", "2024-02-01", "invalid") // false
*/
function isBetweenDate(date, start, end, options) {
try {
if (!isOptionsArgument(options)) return false;
const inclusiveStart = booleanOption(options?.inclusiveStart, true);
const inclusiveEnd = booleanOption(options?.inclusiveEnd, true);
const d = plainDateOf(date);
const s = plainDateOf(start);
const e = plainDateOf(end);
if (d === null || s === null || e === null) return false;
try {
if (Temporal.PlainDate.compare(s, e) === 1) return false;
const startCheck = inclusiveStart ? Temporal.PlainDate.compare(s, d) <= 0 : Temporal.PlainDate.compare(s, d) < 0;
const endCheck = inclusiveEnd ? Temporal.PlainDate.compare(d, e) <= 0 : Temporal.PlainDate.compare(d, e) < 0;
return startCheck && endCheck;
} catch {
return false;
}
} catch {
return false;
}
}
export { isBetweenDate };