@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.
77 lines (75 loc) • 4.41 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { isOptionsArgument } from "../../internal/isObject.js";
import { plainUntilWithRounding } from "../../internal/zonedDifference/nudgeWindow.js";
import { isValidDateTimeDurationUnit } from "../validate/isValidDateTimeDurationUnit.js";
import { resolveDurationUnit } from "../../internal/resolveDurationUnit.js";
import { isValidDateTime } from "../validate/isValidDateTime.js";
import { differenceRecord } from "../../internal/differenceRecord.js";
import { getLargestDateTimeDurationUnit } from "./getLargestDateTimeDurationUnit.js";
// src/plain/calculate/diffDateTime.ts
/**
* Return the difference between two PlainDateTime values in the requested unit.
*
* - Returns `null` for invalid inputs (negative diffs are valid).
* - Uses Temporal.PlainDateTime.until and extracts the requested unit.
*
* `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 }`.
* - Nanosecond precision: the result is a JavaScript `number`, so it stops being exact once it
* passes `Number.MAX_SAFE_INTEGER` — about 104 days in nanoseconds and about 285 years in
* microseconds. `diffDateTime("2024-01-01T00:00:00", "2024-04-15T00:00:00.000000001", "nanoseconds")`
* returns `9072000000000000` rather than `9072000000000001`. For an exact count use the `bigint` APIs: `spanNs`
* in `span/`, or `toNanoseconds` in `precision/`.
*
* @param dateTime1 ISO PlainDateTime string for the start
* @param dateTime2 ISO PlainDateTime string for the end
* @param units DateTimeDurationUnit | DateTimeDurationUnit[] to measure the difference
* @param options optional: 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 diffDateTime("2024-03-10T12:00:00", "2024-03-15T12:00:00", "days") // 5
* @example diffDateTime("invalid", "2024-03-15T12:00:00", "days") // null
* @example diffDateTime("2024-01-01T00:00:00", "2025-03-01T00:00:00", ["years", "days"]) // { years: 1, days: 59 } (P1Y2M; the 2 months are carried into days)
*/
function diffDateTime(dateTime1, dateTime2, units, options) {
try {
if (!isOptionsArgument(options)) return null;
const validDateTimes = isValidDateTime(dateTime1) && isValidDateTime(dateTime2);
const resolved = Array.isArray(units) ? units.map((unit) => resolveDurationUnit(unit)) : resolveDurationUnit(units);
const isSingleUnit = !Array.isArray(resolved);
const validUnits = isSingleUnit ? isValidDateTimeDurationUnit(resolved) : resolved.every(isValidDateTimeDurationUnit);
if (!validDateTimes || !validUnits) return null;
try {
const largestUnit = isSingleUnit ? resolved : getLargestDateTimeDurationUnit(resolved);
if (largestUnit === "") return null;
const dt1 = Temporal.PlainDateTime.from(dateTime1);
const dt2 = Temporal.PlainDateTime.from(dateTime2);
const duration = plainUntilWithRounding(dt1, dt2, {
largestUnit,
smallestUnit: options?.smallestUnit,
roundingIncrement: options?.roundingIncrement,
roundingMode: options?.roundingMode
});
if (isSingleUnit) return duration[resolved] ?? 0;
return differenceRecord(dt1, duration, resolved, {
add: (from, amount) => from.add(amount),
until: (from, to, largest) => from.until(to, { largestUnit: largest })
});
} catch {
return null;
}
} catch {
return null;
}
}
export { diffDateTime };