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.
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.
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);
}PT2H
PT1H
PT2H30M
P2DT2H
P1M12D
P1M9D
RangeError: Temporal error: largestUnit when rounding Duration was not the largest provided unitsmallestUnit: '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.