UNPKG

@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.67 kB
import { Temporal } from "../../internal/temporal.js"; import { countZonedBuckets } from "../../internal/zonedBucket.js"; import { isValidDateTimeUnit } from "../../plain/validate/isValidDateTimeUnit.js"; import { resolveDateTimeUnit } from "../../internal/resolveDateTimeUnit.js"; import { isValidUtc } from "../validate/isValidUtc.js"; // src/utc/interval/intervalCountUtc.ts /** * Count how many `unit` boundaries a UTC interval crosses. * * - Counts calendar boundaries touched by the half-open interval `[start, end)` — distinct * from `diffUtc`, which measures exact elapsed duration. An interval from 23:59 to 00:01 is * two minutes long but touches 2 day boundaries. * - The end boundary is excluded: midnight to midnight two days later counts 2 days. * - A zero-length interval (`start === end`) returns `0`: the empty `[start, start)` holds no instant, * so it touches no unit (before 1.16.0 it counted 1 when mid-unit). * - Boundaries are UTC boundaries — no DST is involved. * - Weeks start on Monday (ISO 8601). * - Accepts singular or plural units (`"day"` and `"days"` behave identically). * - Returns `null` on invalid input (unparseable start/end, `start > end`, unsupported unit, * leap-second strings). * * @param start ISO UTC datetime string for the interval start * @param end ISO UTC datetime string for the interval end * @param unit unit string — any `DateTimeUnit` * @returns number of unit boundaries touched, or null on invalid input * * @example intervalCountUtc("2024-01-01T23:59:00Z", "2024-01-02T00:01:00Z", "day") // 2 * @example intervalCountUtc("2024-01-01T00:00:00Z", "2024-01-03T00:00:00Z", "day") // 2 * @example intervalCountUtc("2024-01-15T00:00:00Z", "2024-03-10T00:00:00Z", "month") // 3 * @example intervalCountUtc("2024-01-01T05:00:00Z", "2024-01-01T05:00:00Z", "day") // 0 (zero-length: holds no instant) * @example intervalCountUtc("invalid", "2024-01-02T00:00:00Z", "day") // null */ function intervalCountUtc(start, end, unit) { if (typeof start !== "string" || typeof end !== "string") return null; if (!isValidUtc(start) || !isValidUtc(end)) return null; if (typeof unit !== "string") return null; const resolvedUnit = resolveDateTimeUnit(unit); if (!isValidDateTimeUnit(resolvedUnit)) return null; try { const startVal = Temporal.Instant.from(start).toZonedDateTimeISO("UTC"); const endVal = Temporal.Instant.from(end).toZonedDateTimeISO("UTC"); const order = Temporal.ZonedDateTime.compare(startVal, endVal); if (order > 0) return null; if (order === 0) return 0; return countZonedBuckets(startVal, endVal, resolvedUnit); } catch { return null; } } export { intervalCountUtc };