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.

100 lines (98 loc) • 6.28 kB
import { isOptionsArgument } from "../../internal/isObject.js"; import { addToZoned } from "../../internal/zonedWallClockOperations.js"; import { zonedUntil } from "../../internal/zonedWallClockDifference.js"; import { frameZoned, normalizeZoneFrame } from "../../internal/zoneFrame.js"; import { isValidDateTimeDurationUnit } from "../../plain/validate/isValidDateTimeDurationUnit.js"; import { resolveDurationUnit } from "../../internal/resolveDurationUnit.js"; import { resolveUnixEpochUnit, unixEpochToInstant } from "../../internal/unixEpochValue.js"; import { differenceRecord } from "../../internal/differenceRecord.js"; import { getLargestDateTimeDurationUnit } from "../../plain/calculate/getLargestDateTimeDurationUnit.js"; // src/unix/calculate/diffUnix.ts /** * Return the difference between two Unix timestamps measured in the given unit. * * - Converts both epochs to a `Temporal.ZonedDateTime` in `timeZone` and uses its `until()`, so * calendar units (days, weeks, months, years) are measured on that zone's wall clock — a * 23-hour DST day is 1 day — while time units (hours and smaller) are exact elapsed time. * `Temporal.Instant.until()` is not used: it rejects every calendar `largestUnit`. * - Supports single unit or array of units. * - Returns null for invalid input. * * `smallestUnit`, `roundingIncrement`, and `roundingMode` control optional rounding of the result, * per Temporal's DifferenceOptions — e.g. `{ smallestUnit: "hour", roundingMode: "halfExpand" }` * rounds the difference to the nearest hour before extracting the requested unit. * - When `units` is an array, `smallestUnit` must not be coarser than the largest unit in the * array (e.g. `["days", "hours"]` with `smallestUnit: "week"`) — this combination is rejected by * Temporal and returns null, same as other invalid input. * - With an array of units, the record is the whole difference: the largest listed unit is * Temporal's `largestUnit`, and the amount of each unlisted unit between two listed units is * carried into the next smaller listed unit, measured from the start moved by the larger listed * amounts (so adding the record to the start reaches the end). Units smaller than the smallest * listed unit are truncated, as for a single unit. For example, `["years", "days"]` over * 1 year 59 days returns `{ years: 1, days: 59 }`. * Days carried into a time unit follow the wall clock of `timeZone` (a 23-hour DST day is * 23 hours). * - Nanosecond precision: the result is a JavaScript `number`, so past about 104 days a * nanosecond count exceeds `Number.MAX_SAFE_INTEGER`. Every value this function can return is * still exact — its inputs are whole milliseconds or seconds — but it is no longer a safe * integer, so arithmetic on it silently loses nanoseconds: * `diffUnix(0, 9072000000, "nanoseconds")` returns `9072000000000000`, and adding `1` to that * gives the same number back. For an exact count use the `bigint` APIs: `spanNs` in `span/`, * or `toNanoseconds` in `precision/`. * - Each value is a safe integer or a digit string (`"1706659200000"`); anything else is invalid. * - Unit names may be singular or plural (`"day"` or `"days"`), as in Temporal; a record result * keeps the plural keys. * - **Limit at an offset with seconds.** The instant is placed in the offset's whole-minute zone, * moved by its seconds, and the moved instant must be inside Temporal's range. So within the * offset's seconds (under a minute) of the last instant Temporal supports * (`+275760-09-13T00:00:00Z`) for an offset east of UTC, or of the first * (`-271821-04-20T00:00:00Z`) for one west, this returns `null`. An offset to the minute has no * such limit. * * @param value1 first Unix epoch: a safe integer, or a string of optionally negative ASCII digits * @param value2 second Unix epoch, in the same form and unit * @param units DateTimeDurationUnit | DateTimeDurationUnit[] to measure the difference * @param options optional: how the epochs are read and how the difference is rounded; a non-object value (such as `null`) is invalid * @returns numeric difference in the requested unit, or null on invalid input * * @example diffUnix(1706745600000, 1706659200000, "days", { timeZone: "UTC" }) // -1 (measured from the first value to the second) * @example diffUnix(1706745600, 1706659200, "days", { epochUnit: "seconds", timeZone: "UTC" }) // -1 * @example diffUnix(0, -86400000, "days", { timeZone: "UTC" }) // -1 (1970-01-01 until 1969-12-31 is minus one day) * @example diffUnix(NaN, 0, "days") // null * @example diffUnix("0", "90000000", ["day", "hour"]) // { days: 1, hours: 1 } (digit strings, singular names with plural keys, UTC by default) * @example diffUnix(1704067200000, 1740787200000, ["years", "days"], { timeZone: "UTC" }) // { years: 1, days: 59 } (P1Y2M; the 2 months are carried into days) */ function diffUnix(value1, value2, units, options) { try { if (!isOptionsArgument(options)) return null; const epochUnit = resolveUnixEpochUnit(options?.epochUnit); const frame = normalizeZoneFrame(options?.timeZone); if (frame === null || epochUnit === null) return null; const plurals = (Array.isArray(units) ? units : [units]).map((unit) => typeof unit === "string" ? resolveDurationUnit(unit) : ""); if (!plurals.every(isValidDateTimeDurationUnit)) return null; const instant1 = unixEpochToInstant(value1, epochUnit); const instant2 = unixEpochToInstant(value2, epochUnit); if (instant1 === null || instant2 === null) return null; const largestUnit = getLargestDateTimeDurationUnit(plurals); if (largestUnit === "") return null; try { const duration = zonedUntil(frameZoned(instant1, frame), frameZoned(instant2, frame), { largestUnit, smallestUnit: options?.smallestUnit, roundingIncrement: options?.roundingIncrement, roundingMode: options?.roundingMode }); if (!Array.isArray(units)) return duration[plurals[0]] ?? 0; const start = frameZoned(instant1, frame); return differenceRecord(start, duration, plurals, { add: (from, amount) => addToZoned(from, amount), until: (from, to, largest) => zonedUntil(from, to, { largestUnit: largest }) }); } catch { return null; } } catch { return null; } } export { diffUnix };