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