@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.
52 lines (50 loc) • 2.33 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { isOptionsArgument } from "../../internal/isObject.js";
import { optionOrDefault } from "../../internal/optionOrDefault.js";
import { isValidTime } from "../validate/isValidTime.js";
// src/plain/compare/isBetweenTime.ts
/**
* Return true when `time` is between `start` and `end` (inclusive by default).
*
* - Uses Temporal.PlainTime.compare to compare times.
* - Returns false if start > end (invalid range).
* - Returns false if any input is invalid.
* - Note: PlainTime comparison does not account for day overflow.
*
* @param time ISO PlainTime string to check
* @param start ISO PlainTime string for the start of the range
* @param end ISO PlainTime string for the end of the range
* @param options Whether each end of the range counts as inside it
* @returns boolean indicating whether time is between start and end
*
* @example isBetweenTime("12:34:56", "12:00:00", "13:00:00") // true
* @example isBetweenTime("12:34:56", "12:34:56", "13:00:00") // true
* @example isBetweenTime("12:34:56", "12:34:57", "13:00:00") // false
* @example isBetweenTime("12:34:56", "12:00:00", "12:34:56") // true
* @example isBetweenTime("12:34:56", "12:00:00", "12:34:55") // false
* @example isBetweenTime("invalid", "12:00:00", "13:00:00") // false
* @example isBetweenTime("12:34:56", "invalid", "13:00:00") // false
* @example isBetweenTime("12:34:56", "12:00:00", "invalid") // false
*/
function isBetweenTime(time, start, end, options) {
try {
if (!isOptionsArgument(options)) return false;
const inclusiveStart = optionOrDefault(options?.inclusiveStart, true);
const inclusiveEnd = optionOrDefault(options?.inclusiveEnd, true);
if (!isValidTime(time) || !isValidTime(start) || !isValidTime(end)) return false;
try {
const t = Temporal.PlainTime.from(time);
const s = Temporal.PlainTime.from(start);
const e = Temporal.PlainTime.from(end);
if (Temporal.PlainTime.compare(s, e) === 1) return false;
const startCheck = inclusiveStart ? Temporal.PlainTime.compare(s, t) <= 0 : Temporal.PlainTime.compare(s, t) < 0;
const endCheck = inclusiveEnd ? Temporal.PlainTime.compare(t, e) <= 0 : Temporal.PlainTime.compare(t, e) < 0;
return startCheck && endCheck;
} catch {
return false;
}
} catch {
return false;
}
}
export { isBetweenTime };