@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.
48 lines (46 loc) • 2.73 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { isOptionsArgument } from "../../internal/isObject.js";
import { optionOrDefault } from "../../internal/optionOrDefault.js";
import { normalizeZoneFrame } from "../../internal/zoneFrame.js";
import { resolveUnixEpochUnit, unixEpochToInstant } from "../../internal/unixEpochValue.js";
// src/unix/calculate/isBetweenUnix.ts
/**
* Return true when the Unix timestamp is between start and end (inclusive by default).
*
* - Uses Temporal.Instant.compare for comparison.
* - Returns false if start > end or inputs are invalid.
* - Each value is a safe integer or a digit string (`"1705000000000"`); anything else returns false.
*
* @param value Unix epoch to check: a safe integer, or a string of optionally negative ASCII digits
* @param start Unix epoch for range start, in the same form and unit
* @param end Unix epoch for range end, in the same form and unit
* @param options optional: how the epochs are read and whether each end of the range is included
* @returns boolean indicating whether value is between start and end
*
* @example isBetweenUnix(1705000000000, 1704000000000, 1706000000000) // true
* @example isBetweenUnix(1705000000, 1704000000, 1706000000, { epochUnit: "seconds" }) // true
* @example isBetweenUnix(1703000000000, 1704000000000, 1706000000000) // false
* @example isBetweenUnix("1705000000", "1704000000", "1706000000", { epochUnit: "second" }) // true (digit strings)
* @example isBetweenUnix(1705000000000, 1704000000000, 1706000000000, { timeZone: "Mars/Olympus" }) // false (unknown zone)
*/
function isBetweenUnix(value, start, end, options) {
try {
if (!isOptionsArgument(options)) return false;
const epochUnit = resolveUnixEpochUnit(options?.epochUnit);
const frame = normalizeZoneFrame(options?.timeZone);
const inclusiveStart = optionOrDefault(options?.inclusiveStart, true);
const inclusiveEnd = optionOrDefault(options?.inclusiveEnd, true);
if (frame === null || epochUnit === null) return false;
const instant = unixEpochToInstant(value, epochUnit);
const startInstant = unixEpochToInstant(start, epochUnit);
const endInstant = unixEpochToInstant(end, epochUnit);
if (instant === null || startInstant === null || endInstant === null) return false;
if (Temporal.Instant.compare(startInstant, endInstant) === 1) return false;
const startCheck = inclusiveStart ? Temporal.Instant.compare(startInstant, instant) <= 0 : Temporal.Instant.compare(startInstant, instant) < 0;
const endCheck = inclusiveEnd ? Temporal.Instant.compare(instant, endInstant) <= 0 : Temporal.Instant.compare(instant, endInstant) < 0;
return startCheck && endCheck;
} catch {
return false;
}
}
export { isBetweenUnix };