@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.
44 lines (42 loc) • 2.64 kB
JavaScript
import { instantOf } from "../../internal/instantNanoseconds.js";
// src/transport/compare/scheduleDeviation.ts
/**
* Measure how far an actual time is from its plan: positive when late, negative when early.
*
* Every mode publishes a plan and records what happened, and measures the gap the same way. This
* is that gap; `classifyPunctuality` judges it against a tolerance.
*
* - **Exact elapsed time**, as an ISO 8601 duration with hours as the largest unit, so the value
* never depends on a calendar or a wall clock. A delay across a fall-back night is `PT1H`,
* never the `PT0S` a wall-clock subtraction reads; across a spring-forward it is `PT1H`, never
* `PT2H`. Two days late is `PT48H`, not `P2D`.
* - **Signed:** `actual` after `planned` is positive (late), before it negative (`"-PT5M"`,
* early), and equal is `"PT0S"`.
* - Both arguments are exact instants (`Z`/offset) with no annotation of any kind. The offset
* each is written in does not matter. To show a schedule's local time, use `etaAtZone`.
* - Returns `""` on invalid input, including a zoneless wall time, which is not a moment.
*
* @param planned ISO 8601 instant string of the planned time
* @param actual ISO 8601 instant string of the actual (or compared) time
* @returns ISO 8601 duration from planned to actual, negative when early, or "" on invalid input
*
* @example scheduleDeviation("2024-06-15T10:00:00Z", "2024-06-15T10:14:00Z") // "PT14M"
* @example scheduleDeviation("2024-06-15T10:00:00Z", "2024-06-15T09:55:00Z") // "-PT5M" (five minutes early)
* @example scheduleDeviation("2024-06-15T10:00:00Z", "2024-06-15T10:00:00Z") // "PT0S"
* @example scheduleDeviation("2024-06-15T10:00:00Z", "2024-06-17T11:30:00Z") // "PT49H30M" (hours, never days)
* @example scheduleDeviation("2024-04-07T02:30:00+11:00[Australia/Sydney]", "2024-04-07T02:30:00+10:00[Australia/Sydney]") // "" (a zoned string is not an instant; write the offsets: "2024-04-07T02:30:00+11:00" to "2024-04-07T02:30:00+10:00" is "PT1H" across the fall-back)
* @example scheduleDeviation("2024-06-15T10:00:00Z", "2024-06-15T12:14:00+02:00") // "PT14M" (the offset it is written in does not matter)
* @example scheduleDeviation("2024-06-15T10:00:00", "2024-06-15T10:14:00Z") // "" (a zoneless plan is not a moment)
*/
function scheduleDeviation(planned, actual) {
try {
const plannedInstant = instantOf(planned);
if (plannedInstant === null) return "";
const actualInstant = instantOf(actual);
if (actualInstant === null) return "";
return plannedInstant.until(actualInstant, { largestUnit: "hours" }).toString();
} catch {
return "";
}
}
export { scheduleDeviation };