Durations
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,subtractZonedand 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 asintervalFromDurationUtc.
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 below.
This guide covers the duration functions. To add, subtract and diff dates, see Plain Arithmetic.
Validate and parse
Section titled “Validate and parse”import { isValidDuration, parseDuration } from "@northguild/gmt";
isValidDuration("P1DT2H30M"); // trueisValidDuration("not a duration"); // false
parseDuration("P1DT2H30M"); // "P1DT2H30M"parseDuration("PT1.5S", { smallestUnit: "second", roundingMode: "trunc" });// "PT1S"Read a duration people write
Section titled “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 page.
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 grammarNo string is valid in both forms, so a caller that takes either one chains the parsers:
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:
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:
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 runs both parsers on a string you type.
Round a duration’s output precision
Section titled “Round a duration’s output precision”parseDuration("PT1.5S", { smallestUnit: "second" }); // "PT1S"parseDuration("PT1.5S", { fractionalSecondDigits: 3 }); // "PT1.500S"parseDuration("PT1.9S", { smallestUnit: "second", roundingMode: "trunc" }); // "PT1S"Combine two durations
Section titled “Combine two durations”import { addDuration, subtractDuration } from "@northguild/gmt";
addDuration("P1D", "PT2H"); // "P1DT2H"subtractDuration("P1D", "PT2H"); // "PT22H"subtractDuration("PT1H", "PT2H"); // "-PT1H"Roll small units into larger ones
Section titled “Roll small units into larger ones”import { normalizeDuration } from "@northguild/gmt";
normalizeDuration("PT90M", { largestUnit: "hour" }); // "PT1H30M"normalizeDuration("PT90M30S", { smallestUnit: "minute" }); // "PT91M"normalizeDuration("PT90M"); // "PT90M" — no options = no promotionnormalizeDuration("P45D", { largestUnit: "month", relativeTo: "2024-01-01" });// "P1M14D" — calendar units need a relativeTo anchorRead one component vs. total into a unit
Section titled “Read one component vs. total into a unit”getDurationUnit reads one component as stored. totalDuration converts the whole duration
into one unit:
import { getDurationUnit, totalDuration } from "@northguild/gmt";
getDurationUnit("P1DT2H30M", "hours"); // 2 — the hours component as storedtotalDuration("P1DT2H30M", "hours"); // 26.5 — the whole duration totalled into hourstotalDuration("PT90M", "hours"); // 1.5
totalDuration("P1M", "days"); // null — calendar unit needs relativeTototalDuration("P1M", "days", { relativeTo: "2024-02-01" }); // 29getDurationUnit("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"):
import { getUtcNow, getZonedNow, totalDuration } from "@northguild/gmt";
totalDuration("P1Y", "seconds", { relativeTo: getUtcNow() }); // null — a Z string is refusedtotalDuration("P1Y", "seconds", { relativeTo: getZonedNow("UTC") }); // 31622400 — from a clock at 2027-06-15T12:07:30ZUnit objects
Section titled “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
Section titled “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:
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 seconddurationFromUnits({ minutes: 90 }); // "PT90M" — written as given, not carried into hoursdurationFromUnits({}); // "" — an empty object is invalid inputThe result goes straight into any function that takes a duration string:
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 hoursTotal a unit object in one unit
Section titled “Total a unit object in one unit”totalUnits converts the whole object into one unit, as totalDuration does for a string:
import { totalUnits } from "@northguild/gmt";
totalUnits({ minutes: 15 }, "seconds"); // 900totalUnits({ days: 30 }, "seconds"); // 2592000totalUnits({ days: 1, hours: 12 }, "seconds"); // 129600totalUnits({ hours: 36 }, "days"); // 1.5totalUnits({ minutes: -90 }, "hours"); // -1.5totalUnits 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:
import { durationFromUnits, totalDuration, totalUnits } from "@northguild/gmt";
totalUnits({ weeks: 1 }, "days"); // null — a week is not an exact unittotalUnits({ 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 dateTypeScript 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
Section titled “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, thentotalDurationwithrelativeTo. - A length counted from now:
getUnixInfor an epoch,getUtcInfor UTC text,formatHttpDateFromNowfor an HTTP date,totalUnitsFromNowfor seconds (or any one unit) andttlFromNowfor all of them from one clock read. The Expiry Calculator shows all four forms for one length. - Seconds until a stored moment:
secondsUntilUnix,secondsUntilHttpDateorsecondsUntilRetryAfter.
A length of time counted from now
Section titled “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.
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 epochgetUtcIn({ days: 90 }); // "2027-09-13T12:07:30Z" — UTC textformatHttpDateFromNow({ days: 90 }); // "Mon, 13 Sep 2027 12:07:30 GMT" — an HTTP datetotalUnitsFromNow({ days: 90 }, "seconds"); // 7776000 — seconds, for a Max-AgettlFromNow({ 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:
import { getZonedNow, parseHumanDuration, totalDuration } from "@northguild/gmt";
totalDuration(parseHumanDuration("1y"), "seconds", { relativeTo: getZonedNow("UTC") });// 31622400 — from a clock at 2027-06-15T12:07:30ZA 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:
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:30ZA 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.
import { totalUnitsFromNow } from "@northguild/gmt";
const delay = totalUnitsFromNow({ minutes: 5 }, "milliseconds"); // 300000if (delay !== null) setTimeout(refresh, delay);Seconds until a stored moment
Section titled “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:
import { secondsUntilUnix } from "@northguild/gmt";
// With a clock at 2027-06-15T12:07:30Z:secondsUntilUnix(1813061370, { epochUnit: "seconds" }); // 120secondsUntilUnix(1813061130, { epochUnit: "seconds" }); // -120 — already pastsecondsUntilUnix("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":
import { durationFromUnits, formatHumanDuration, normalizeDuration,} from "@northguild/gmt";
const left = 259200; // from secondsUntilUnix(exp, { epochUnit: "seconds" }), once not null and above 0formatHumanDuration( 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:
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:
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:
import { roundUnix, roundUtc } from "@northguild/gmt";
roundUnix(1813061765123, { smallestUnit: "minute", roundingIncrement: 15, roundingMode: "floor" });// 1813061700000roundUtc("2027-06-15T12:07:30.5Z", { smallestUnit: "minute", roundingIncrement: 15, roundingMode: "floor" });// "2027-06-15T12:00:00Z"Sign operations
Section titled “Sign operations”import { negateDuration, absDuration, getDurationSign } from "@northguild/gmt";
negateDuration("P1DT2H"); // "-P1DT2H"absDuration("-P1DT2H"); // "P1DT2H"getDurationSign("-P1DT2H"); // -1getDurationSign("PT0S"); // 0Compare two durations by length
Section titled “Compare two durations by length”import { compareDurations } from "@northguild/gmt";
compareDurations("PT1H", "PT30M"); // 1compareDurations("PT60M", "PT1H"); // 0 — equal by length, not spellingcompareDurations("P1M", "P30D", { relativeTo: "2024-01-01" }); // 1compareDurations("P1M", "P30D", { relativeTo: "2024-02-01" }); // -1compareDurations("P1M", "P30D"); // null — a calendar unit needs a relativeTo anchorRender as human-readable text
Section titled “Render as human-readable text”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 omittedBridge a diff into a duration string
Section titled “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:
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 hoursdiffDateAsDuration/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:
import { diffDate, diffDateAsDuration } from "@northguild/gmt";
diffDate("not a date", "2024-04-05", "days"); // nulldiffDateAsDuration("not a date", "2024-04-05", "days"); // ""Feed the result straight into any duration function:
formatDuration(diffDateAsDuration(a, b, "days"), "en-US").
See also
Section titled “See also”- Plain Arithmetic — date arithmetic with
{ unit: number }objects - Calendar Systems — calendar-aware duration arithmetic
parseDurationreferenceformatDurationreferencetotalDurationreferencetotalUnitsreferencedurationFromUnitsreferencediffDateAsDurationreference
© 2026 NorthGuild · Licences
Code examples: MIT-0. Packages: MIT. Third-party data and components: their own licences, credited where they appear. Everything else: © 2026 NorthGuild, all rights reserved.