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.

45 lines (43 loc) • 2.28 kB
import { durationTotal } from "../../internal/zonedWallClockDifference.js"; import { isDateTimeUnitName } from "../../internal/unitNames.js"; import { resolveDateTimeUnit } from "../../internal/resolveDateTimeUnit.js"; import { dateTimeIntervalOf } from "../../internal/intervalChecks.js"; // src/plain/interval/intervalLengthDateTime.ts /** * Return the exact length of a datetime interval in `unit`, as a real (possibly fractional) number. * * - Distinct from `intervalCountDateTime`, which counts calendar/clock `unit` boundaries * *crossed* rather than measuring exact duration — an interval from 23:59 to 00:01 touches 2 * day boundaries via `intervalCountDateTime` but has an exact length of ~0.0014 days via * `intervalLengthDateTime`. * - Uses `Temporal.Duration.prototype.total`, which resolves calendar units (month, year) * against the interval's own start so a partial month is expressed as a true fraction rather * than truncated. * - Returns `0` for a zero-length interval (`start === end`). * - Returns `null` on invalid input (unparseable start/end, `start > end`, unsupported unit). * * @param start ISO PlainDateTime string for the interval start * @param end ISO PlainDateTime string for the interval end * @param unit unit string — any `DateTimeUnit` * @returns exact length of the interval expressed in `unit`, or null on invalid input * * @example intervalLengthDateTime("2024-01-01T23:59:00", "2024-01-02T00:01:00", "day") // 0.001388888888888889 * @example intervalLengthDateTime("2024-01-01T23:59:00", "2024-01-02T00:01:00", "minute") // 2 * @example intervalLengthDateTime("2024-01-01T00:00:00", "2024-01-01T00:00:00", "day") // 0 * @example intervalLengthDateTime("invalid", "2024-01-02T00:00:00", "day") // null */ function intervalLengthDateTime(start, end, unit) { if (typeof unit !== "string") return null; const resolvedUnit = resolveDateTimeUnit(unit); if (!isDateTimeUnitName(resolvedUnit)) return null; const bounds = dateTimeIntervalOf(start, end); if (bounds === null) return null; try { const [startVal, endVal] = bounds; const duration = startVal.until(endVal, { largestUnit: resolvedUnit }); return durationTotal(duration, resolvedUnit, startVal); } catch { return null; } } export { intervalLengthDateTime };