Skip to content
jshacks.dev
Fundamentals

Round a duration with Temporal.Duration

Round a Temporal.Duration to hours with round and smallestUnit, and see why days and months need a relativeTo argument. Node.js 26.

2 min read
Summarize in AI

A job that ran for 1 hour 50 minutes should read 2h on a dashboard. Temporal.Duration.round() does the rounding, with a rounding mode you choose, in Node.js 26.

JavaScript
const elapsed = Temporal.Duration.from({ hours: 1, minutes: 50 });

console.log(elapsed.round({ smallestUnit: 'hour', roundingMode: 'halfExpand' }).toString());
console.log(elapsed.round({ smallestUnit: 'hour', roundingMode: 'floor' }).toString());
console.log(Temporal.Duration.from({ minutes: 150 }).round({ largestUnit: 'hours' }).toString());
console.log(Temporal.Duration.from({ hours: 50 }).round({ largestUnit: 'days' }).toString());

const forty = Temporal.Duration.from({ days: 40 });
console.log(forty.round({ largestUnit: 'months', relativeTo: '2026-02-01' }).toString());
console.log(forty.round({ largestUnit: 'months', relativeTo: '2026-03-01' }).toString());

try {
  forty.round({ largestUnit: 'months' });
} catch (error) {
  console.log(error.name + ': ' + error.message);
}
Text
PT2H
PT1H
PT2H30M
P2DT2H
P1M12D
P1M9D
RangeError: Temporal error: largestUnit when rounding Duration was not the largest provided unit

smallestUnit: 'hour' drops the minutes, and the default mode, halfExpand, rounds 1h50 to PT2H. roundingMode: 'floor' gives PT1H. largestUnit: 'hours' goes the other way, converting 150 minutes to PT2H30M, and 50 hours with largestUnit: 'days' is P2DT2H. Months are different, because a month is not a fixed number of days. The same 40 days is P1M12D counted from 1 February and P1M9D from 1 March, and without a relativeTo date the call throws a RangeError, the last line. Its text talks about largestUnit, which is misleading: the missing piece is relativeTo. The rules are in the Temporal documentation for Duration.

The output prints in ISO 8601 duration form, so use Intl.DurationFormat to show it to a person. Not available in Node.js 24, and a duration of { hours: 50 } is not P2D until you ask for it.

Taggednode 26
Share

More snippets

Fundamentals

Sort dates in an array

Sort an array of Date objects by subtracting them, and see why the default sort orders dates by weekday name. Works in every Node.js release.

1 min read
Fundamentals

Sort by multiple keys

Sort records by several keys in one comparator with toSorted, falling through to the next key when the first ties. Needs Node.js 20, stable since ES2019.

1 min read
Fundamentals

Get a random item from an array

Pick a random item from an array with Math.random, and see why rounding the index instead of flooring it makes the middle item twice as likely. Node.js 18.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.