# Durations

Industry: Core

An amount of time has two shapes in GMT:

- A **unit object**, such as `{ minutes: 15 }` or `{ days: 1, hours: 12 }`. The date arithmetic
  functions take one: `addDate`, `subtractZoned` and their siblings.
- An **ISO 8601 duration string**, such as `"PT15M"` or `"P1DT12H"`. The duration functions take
  one, and so do the other functions that take a duration, such as `intervalFromDurationUtc`.

`durationFromUnits` writes a unit object as a duration string, so an amount you hold as an object
works with every function that takes a string. `totalUnits` totals a unit object in one call. Both
are under [Unit objects](#unit-objects) below.

This guide covers the duration functions. To add, subtract and diff dates, see
[Plain Arithmetic](../plain-arithmetic/).

## Validate and parse

```typescript
import { isValidDuration, parseDuration } from "@northguild/gmt";

isValidDuration("P1DT2H30M"); // true
isValidDuration("not a duration"); // false

parseDuration("P1DT2H30M"); // "P1DT2H30M"
parseDuration("PT1.5S", { smallestUnit: "second", roundingMode: "trunc" });
// "PT1S"
```

## Read a duration people write

`parseDuration` reads ISO 8601 only. A timeout in a config file or a charter party is written
`2h 30m`, `1.5h` or `3 days`. `parseHumanDuration` reads that form under a grammar the library
publishes, and returns the same ISO 8601 string, or `""` for anything outside the grammar. The
grammar is on the [`parseHumanDuration`](/gmt/reference/duration/parse/parseHumanDuration/) page.

```ts
import { parseDuration, parseHumanDuration } from "@northguild/gmt/duration/parse";

parseHumanDuration("2h 30m"); // "PT2H30M"
parseHumanDuration("1.5h"); // "PT1H30M"
parseHumanDuration("3 days"); // "P3D"
parseHumanDuration("PT2H30M"); // "" — ISO 8601 is not in this grammar
```

No string is valid in both forms, so a caller that takes either one chains the parsers:

```ts
const read = (s: string) => parseDuration(s) || parseHumanDuration(s);

read("2h 30m"); // "PT2H30M"
read("P1M"); // "P1M"
read("nonsense"); // ""
```

**A letter is a minute or a month by its form.** In the human grammar `m` and `M` are a minute and
`mo` is a month. ISO 8601 puts the minute after the `T` and the month before it, so `P1M` is a month.
The human parser refuses `P1M`:

```ts
parseHumanDuration("1m"); // "PT1M"
parseHumanDuration("1mo"); // "P1M"
parseHumanDuration("P1M"); // ""
parseDuration("P1M"); // "P1M"
```

**Nothing is balanced.** `formatHumanDuration` writes the units it was given, so `PT90M` is `90m`.
Run `normalizeDuration` first to carry the minutes into hours:

```ts
import { formatHumanDuration } from "@northguild/gmt/duration/format";
import { normalizeDuration } from "@northguild/gmt/duration/normalize";

formatHumanDuration("PT90M"); // "90m"
formatHumanDuration(normalizeDuration("PT90M", { largestUnit: "hour" })); // "1h 30m"
```

The [Duration Parser Bench](/gmt/tools/duration-parser-bench/) runs both parsers on a string you type.

## Round a duration's output precision

```typescript
parseDuration("PT1.5S", { smallestUnit: "second" }); // "PT1S"
parseDuration("PT1.5S", { fractionalSecondDigits: 3 }); // "PT1.500S"
parseDuration("PT1.9S", { smallestUnit: "second", roundingMode: "trunc" }); // "PT1S"
```

## Combine two durations

```typescript
import { addDuration, subtractDuration } from "@northguild/gmt";

addDuration("P1D", "PT2H"); // "P1DT2H"
subtractDuration("P1D", "PT2H"); // "PT22H"
subtractDuration("PT1H", "PT2H"); // "-PT1H"
```

## Roll small units into larger ones

```typescript
import { normalizeDuration } from "@northguild/gmt";

normalizeDuration("PT90M", { largestUnit: "hour" }); // "PT1H30M"
normalizeDuration("PT90M30S", { smallestUnit: "minute" }); // "PT91M"
normalizeDuration("PT90M"); // "PT90M" — no options = no promotion
normalizeDuration("P45D", { largestUnit: "month", relativeTo: "2024-01-01" });
// "P1M14D" — calendar units need a relativeTo anchor
```

## Read one component vs. total into a unit

`getDurationUnit` reads one component **as stored**. `totalDuration` converts the whole duration
into one unit:

```typescript
import { getDurationUnit, totalDuration } from "@northguild/gmt";

getDurationUnit("P1DT2H30M", "hours"); // 2 — the hours component as stored
totalDuration("P1DT2H30M", "hours"); // 26.5 — the whole duration totalled into hours
totalDuration("PT90M", "hours"); // 1.5

totalDuration("P1M", "days"); // null — calendar unit needs relativeTo
totalDuration("P1M", "days", { relativeTo: "2024-02-01" }); // 29
```

`getDurationUnit("PT90M", "hours")` is `0` but `totalDuration("PT90M", "hours")` is `1.5`: the
first reads a stored component, the second totals the whole duration. `totalDuration` returns
`null` when a calendar unit (year, month or week) is involved without a `relativeTo` anchor.
`normalizeDuration` carries the same constraint. `negateDuration`, `absDuration`,
`getDurationSign` and `getDurationUnit` only read the sign or a field, so they never need
an anchor.

A `relativeTo` that is a zoned string starts the count from that moment. A `Z` string, such as
`getUtcNow()` returns, is refused and the call returns `null`, as Temporal refuses it. To start
from now, pass `getZonedNow("UTC")`:

```typescript
import { getUtcNow, getZonedNow, totalDuration } from "@northguild/gmt";

totalDuration("P1Y", "seconds", { relativeTo: getUtcNow() }); // null — a Z string is refused
totalDuration("P1Y", "seconds", { relativeTo: getZonedNow("UTC") }); // 31622400 — from a clock at 2027-06-15T12:07:30Z
```

## Unit objects

Settings and function arguments often hold an amount as an object, such as `{ minutes: 15 }`.
Two functions take that shape.

### Write a unit object as a duration string

`durationFromUnits` writes the object as an ISO 8601 duration string. It takes all ten units,
from years down to nanoseconds:

```typescript
import { durationFromUnits } from "@northguild/gmt";

durationFromUnits({ minutes: 15 }); // "PT15M"
durationFromUnits({ days: 1, hours: 12 }); // "P1DT12H"
durationFromUnits({ years: 1, months: 2 }); // "P1Y2M"
durationFromUnits({ milliseconds: 1500 }); // "PT1.5S" — a decimal fraction of a second
durationFromUnits({ minutes: 90 }); // "PT90M" — written as given, not carried into hours
durationFromUnits({}); // "" — an empty object is invalid input
```

The result goes straight into any function that takes a duration string:

```typescript
import {
  durationFromUnits,
  intervalFromDurationUtc,
  normalizeDuration,
} from "@northguild/gmt";

intervalFromDurationUtc("2024-01-01T00:00:00Z", durationFromUnits({ days: 1 }), "start");
// { start: "2024-01-01T00:00:00Z", end: "2024-01-02T00:00:00Z" }

normalizeDuration(durationFromUnits({ minutes: 90 }), { largestUnit: "hour" });
// "PT1H30M" — normalizeDuration carries the minutes into hours
```

### Total a unit object in one unit

`totalUnits` converts the whole object into one unit, as `totalDuration` does for a string:

```typescript
import { totalUnits } from "@northguild/gmt";

totalUnits({ minutes: 15 }, "seconds"); // 900
totalUnits({ days: 30 }, "seconds"); // 2592000
totalUnits({ days: 1, hours: 12 }, "seconds"); // 129600
totalUnits({ hours: 36 }, "days"); // 1.5
totalUnits({ minutes: -90 }, "hours"); // -1.5
```

`totalUnits` takes exact units only: days, hours, minutes, seconds, milliseconds, microseconds
and nanoseconds. It counts a day as 24 hours, as Temporal's `Duration.prototype.total` does when
it has no `relativeTo`. Temporal gives a year, a month or a week no length without a date to
measure from, so `totalUnits` returns `null` for one, as a key or as the unit to total into:

```typescript
import { durationFromUnits, totalDuration, totalUnits } from "@northguild/gmt";

totalUnits({ weeks: 1 }, "days"); // null — a week is not an exact unit
totalUnits({ days: 7 }, "hours"); // 168 — write the week as seven days

totalDuration(durationFromUnits({ months: 1 }), "days", { relativeTo: "2024-02-01" });
// 29 — a calendar amount: write the string, then total it against a date
```

TypeScript reports `{ weeks: 1 }` as an error where the call is written. A value that only exists
at run time, such as an object parsed from JSON, gets `null`. Check for `null` before you use the
result. Do not default it away: `totalUnits(config.ttl, "seconds") ?? 0` would turn a misspelt
key into a lifetime of zero seconds.

### Which function to use

- **A unit object of exact units, to total in one unit:** `totalUnits`.
- **A unit object of any units, to write as a duration string:** `durationFromUnits`.
- **A duration string, to total in one unit:** `totalDuration`.
- **A unit object with years, months or weeks, to total in one unit:** `durationFromUnits`, then
  `totalDuration` with `relativeTo`.
- **A length counted from now:** `getUnixIn` for an epoch, `getUtcIn` for UTC text,
  `formatHttpDateFromNow` for an HTTP date, `totalUnitsFromNow` for seconds (or any one unit) and
  `ttlFromNow` for all of them from one clock read. The
  [Expiry Calculator](/gmt/tools/expiry-calculator/) shows all four forms for one length.
- **Seconds until a stored moment:** `secondsUntilUnix`, `secondsUntilHttpDate` or
  `secondsUntilRetryAfter`.

## A length of time counted from now

A cookie lifetime, a token expiry or a timer delay is a length counted from the current time.
Each function below reads the clock, takes a unit object and counts in UTC, so the result does not
change with the server's zone. A negative amount returns the sentinel, because the name gives the
direction: `getUnixIn` counts forward and `getUnixAgo` counts back.

```typescript
import {
  formatHttpDateFromNow,
  getUnixIn,
  getUtcIn,
  totalUnitsFromNow,
  ttlFromNow,
} from "@northguild/gmt";

// With a clock at 2027-06-15T12:07:30Z:
getUnixIn({ days: 90 }, { epochUnit: "seconds" }); // 1820837250 — an epoch
getUtcIn({ days: 90 }); // "2027-09-13T12:07:30Z" — UTC text
formatHttpDateFromNow({ days: 90 }); // "Mon, 13 Sep 2027 12:07:30 GMT" — an HTTP date
totalUnitsFromNow({ days: 90 }, "seconds"); // 7776000 — seconds, for a Max-Age
ttlFromNow({ days: 1 });
// { seconds: 86400, milliseconds: 86400000, epochSeconds: 1813147650,
//   httpDate: "Wed, 16 Jun 2027 12:07:30 GMT", iso: "2027-06-16T12:07:30Z" }
```

`ttlFromNow` gives every form from one clock read, so a cookie's `Max-Age` and `Expires` name the
same second. The functions take a unit object only. For a length written as a string in a config
file, total it against a zoned start:

```typescript
import { getZonedNow, parseHumanDuration, totalDuration } from "@northguild/gmt";

totalDuration(parseHumanDuration("1y"), "seconds", { relativeTo: getZonedNow("UTC") });
// 31622400 — from a clock at 2027-06-15T12:07:30Z
```

A year is not a fixed number of seconds. From this clock the next 12 months take in 29 February
2028, so they are 366 days and `31_536_000` (365 days) would be a day short.

**Deleting a cookie.** A past `Expires` deletes a cookie (RFC 6265 section 4.1.2). A negative
length is refused, so count back:

```typescript
import { formatHttpDate, getUtcAgo } from "@northguild/gmt";

formatHttpDate(getUtcAgo({ days: 1 })); // "Mon, 14 Jun 2027 12:07:30 GMT" — from a clock at 2027-06-15T12:07:30Z
```

**A timer delay.** `totalUnitsFromNow(units, "milliseconds")` reads the clock once. Do not write
`getUnixIn(units) - getUnixNow()`: it reads the clock twice, and a `null` from `getUnixIn` becomes
`0` in the subtraction, so a bad length looks like a delay of zero.

```typescript
import { totalUnitsFromNow } from "@northguild/gmt";

const delay = totalUnitsFromNow({ minutes: 5 }, "milliseconds"); // 300000
if (delay !== null) setTimeout(refresh, delay);
```

### Seconds until a stored moment

`secondsUntilUnix` (a JWT `exp`), `secondsUntilHttpDate` and `secondsUntilRetryAfter` give the
whole seconds from now until a stored moment, rounded up so a wait of that length never falls
short. A past moment gives a negative number, and `null` means invalid input only. Check `null`
before `Math.max(0, n)`, because `Math.max(0, null)` is `0`:

```typescript
import { secondsUntilUnix } from "@northguild/gmt";

// With a clock at 2027-06-15T12:07:30Z:
secondsUntilUnix(1813061370, { epochUnit: "seconds" }); // 120
secondsUntilUnix(1813061130, { epochUnit: "seconds" }); // -120 — already past
secondsUntilUnix("soon", { epochUnit: "seconds" }); // null — invalid input

const left = secondsUntilUnix(exp, { epochUnit: "seconds" });
const wait = left === null ? null : Math.max(0, left);
```

**"Expires in 3 days".** Total the seconds into days with `normalizeDuration`. Without it the text
is `"259200s"`:

```typescript
import {
  durationFromUnits,
  formatHumanDuration,
  normalizeDuration,
} from "@northguild/gmt";

const left = 259200; // from secondsUntilUnix(exp, { epochUnit: "seconds" }), once not null and above 0
formatHumanDuration(
  normalizeDuration(durationFromUnits({ seconds: left }), { largestUnit: "day" }),
); // "3d"
formatHumanDuration(durationFromUnits({ seconds: left })); // "259200s"
```

**Token leeway.** RFC 7519 section 4.1.4 lets a verifier allow "some small leeway". GMT takes no
option, because the amount is the verifier's policy:

```typescript
const left = secondsUntilUnix(exp, { epochUnit: "seconds" });
const expired = left === null || left + leeway <= 0;
```

**Clock-skew window on a token's `iat`.** All three calls need `epochUnit`, and either end can be
`null`:

```typescript
const lo = getUnixAgo({ seconds: 300 }, { epochUnit: "seconds" });
const hi = getUnixIn({ seconds: 300 }, { epochUnit: "seconds" });
const fresh = lo !== null && hi !== null && isBetweenUnix(iat, lo, hi, { epochUnit: "seconds" });
```

**A fixed window.** `floorToZone` floors to a calendar unit, so a fifteen-minute rate-limit
bucket uses `roundUnix`:

```typescript
import { roundUnix, roundUtc } from "@northguild/gmt";

roundUnix(1813061765123, { smallestUnit: "minute", roundingIncrement: 15, roundingMode: "floor" });
// 1813061700000
roundUtc("2027-06-15T12:07:30.5Z", { smallestUnit: "minute", roundingIncrement: 15, roundingMode: "floor" });
// "2027-06-15T12:00:00Z"
```

## Sign operations

```typescript
import { negateDuration, absDuration, getDurationSign } from "@northguild/gmt";

negateDuration("P1DT2H"); // "-P1DT2H"
absDuration("-P1DT2H"); // "P1DT2H"
getDurationSign("-P1DT2H"); // -1
getDurationSign("PT0S"); // 0
```

## Compare two durations by length

```typescript
import { compareDurations } from "@northguild/gmt";

compareDurations("PT1H", "PT30M"); // 1
compareDurations("PT60M", "PT1H"); // 0 — equal by length, not spelling
compareDurations("P1M", "P30D", { relativeTo: "2024-01-01" }); // 1
compareDurations("P1M", "P30D", { relativeTo: "2024-02-01" }); // -1
compareDurations("P1M", "P30D"); // null — a calendar unit needs a relativeTo anchor
```

## Render as human-readable text

```typescript
import { formatDuration } from "@northguild/gmt";

formatDuration("P1DT2H30M", "en-US");
// "1 day, 2 hours, and 30 minutes"

formatDuration("P1DT2H30M", "en-US", { style: "short" });
// "1 day, 2 hr, & 30 min"

formatDuration("P1DT0H30M", "en-US");
// "1 day and 30 minutes" — zero-valued components omitted
```

## Bridge a diff into a duration string

`diffDate`/`diffDateTime`/etc. return a single-unit number. Their `*AsDuration`
siblings return an ISO 8601 duration string instead:

```typescript
import { diffDateAsDuration, diffZonedAsDuration } from "@northguild/gmt";

diffDateAsDuration("2024-03-10", "2024-04-05", "days");
// "P26D"

diffZonedAsDuration(
  "2024-10-05T12:00:00+10:00[Australia/Sydney]",
  "2024-10-07T12:00:00+11:00[Australia/Sydney]",
  "days",
);
// "P2D" — calendar days on Sydney's wall clock, across a DST spring-forward

diffZonedAsDuration(
  "2024-10-05T12:00:00+10:00[Australia/Sydney]",
  "2024-10-07T12:00:00+11:00[Australia/Sydney]",
  "hours",
);
// "PT47H" — real elapsed time: the spring-forward day had 23 hours
```

`diffDateAsDuration`/`diffDateTimeAsDuration`/`diffZonedAsDuration`/`diffUnixAsDuration`/
`diffUtcAsDuration` are siblings of `diffDate`/`diffDateTime`/`diffZoned`/`diffUnix`/`diffUtc`.
They return an ISO 8601 duration string (sentinel `""`) where the plain functions return a
single-unit number (sentinel `null`). They take a single `unit`, not an array, which sets
the duration's `largestUnit`:

```typescript
import { diffDate, diffDateAsDuration } from "@northguild/gmt";

diffDate("not a date", "2024-04-05", "days"); // null
diffDateAsDuration("not a date", "2024-04-05", "days"); // ""
```

Feed the result straight into any duration function:
`formatDuration(diffDateAsDuration(a, b, "days"), "en-US")`.

## See also

- [Plain Arithmetic](../plain-arithmetic/) — date arithmetic with `{ unit: number }` objects
- [Calendar Systems](../calendar-systems/) — calendar-aware duration arithmetic
- [`parseDuration` reference](/gmt/reference/duration/parse/parseDuration/)
- [`formatDuration` reference](/gmt/reference/duration/format/formatDuration/)
- [`totalDuration` reference](/gmt/reference/duration/calculate/totalDuration/)
- [`totalUnits` reference](/gmt/reference/duration/calculate/totalUnits/)
- [`durationFromUnits` reference](/gmt/reference/duration/calculate/durationFromUnits/)
- [`diffDateAsDuration` reference](/gmt/reference/plain/calculate/diffDateAsDuration/)
