@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.
75 lines (73 loc) • 4.11 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { roundingOptionsOf } from "../../internal/typedOptions.js";
import { plainTimeOf } from "../../internal/inputChecks.js";
import { isOptionsArgument } from "../../internal/isObject.js";
import { isTimeDurationUnitName } from "../../internal/unitNames.js";
import { largestTimeDurationUnit, resolveDurationUnit } from "../../internal/resolveDurationUnit.js";
import { differenceRecord } from "../../internal/differenceRecord.js";
// src/plain/calculate/diffTime.ts
/**
* Return the difference between two PlainTime values in the requested unit.
*
* - Returns `null` for invalid inputs.
* - Uses Temporal.PlainTime.until with `largestUnit` and extracts the requested unit.
*
* `smallestUnit`, `roundingIncrement`, and `roundingMode` control optional rounding of the result,
* per Temporal's DifferenceOptions — e.g. `{ smallestUnit: "minute", roundingMode: "halfExpand" }`
* rounds the difference to the nearest minute before extracting the requested unit.
* - When `units` is an array, `smallestUnit` must not be coarser than the largest unit in the
* array (e.g. `["minutes", "seconds"]` with `smallestUnit: "hour"`) — 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, `["hours", "seconds"]` over
* 1 hour 30 minutes 15 seconds returns `{ hours: 1, seconds: 1815 }`.
* - Nanosecond precision is always exact here, unlike `diffDateTime`/`diffUtc`/`diffUnix`: two
* plain times are less than a day apart, so the widest possible result,
* `diffTime("00:00:00.000000000", "23:59:59.999999999", "nanoseconds")` = `86399999999999`,
* is well inside `Number.MAX_SAFE_INTEGER`. Those three can span more than about 104 days, at
* which point a nanosecond count stops being a safe integer and the `bigint` APIs (`spanNs` in
* `span/`, `toNanoseconds` in `precision/`) are the exact ones.
*
* @param time1 ISO PlainTime string for the start
* @param time2 ISO PlainTime string for the end
* @param units TimeDurationUnit | TimeDurationUnit[] 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 diffTime("12:00:00", "14:30:00", "hours") // 2
* @example diffTime("invalid", "14:30:00", "hours") // null
* @example diffTime("10:00:00", "11:30:15", ["hours", "seconds"]) // { hours: 1, seconds: 1815 } (PT1H30M15S; the 30 minutes are carried into seconds)
*/
function diffTime(time1, time2, units, options) {
try {
if (!isOptionsArgument(options)) return null;
const t1 = plainTimeOf(time1);
const t2 = plainTimeOf(time2);
const resolved = Array.isArray(units) ? units.map((unit) => resolveDurationUnit(unit)) : resolveDurationUnit(units);
const isSingleUnit = !Array.isArray(resolved);
const validUnits = isSingleUnit ? isTimeDurationUnitName(resolved) : resolved.every(isTimeDurationUnitName);
if (t1 === null || t2 === null || !validUnits) return null;
try {
const largestUnit = isSingleUnit ? resolved : largestTimeDurationUnit(resolved);
if (largestUnit === "") return null;
const duration = t1.until(t2, {
largestUnit,
...roundingOptionsOf(options)
});
if (isSingleUnit) return duration[resolved] ?? 0;
const day = Temporal.PlainDate.from("2000-01-01");
return differenceRecord(day.toPlainDateTime(t1), duration, resolved, {
add: (from, amount) => from.add(amount),
until: (from, to, largest) => from.until(to, { largestUnit: largest })
});
} catch {
return null;
}
} catch {
return null;
}
}
export { diffTime };