Sub topic 17
Rounding Values and Durations
This chapter assumes you have read the earlier chapters on Temporal.Duration and on measuring differences with until and since. You should already know how to create a Duration, what balancing does, and what largestUnit controls. Here we cover the round() methods and the rounding options that until and since accept.
Rounding comes up all the time. A timesheet bills in 15-minute blocks, a dashboard shows "about 3 hours ago", and a log viewer cuts timestamps to the second. Temporal handles all three through one set of options, with a few type-specific rules.
The rounding options
Every round() method and every until/since call accepts the same group of options:
| Option | Meaning | Default |
|---|---|---|
| `smallestUnit` | Unit to round to, such as `'minute'` or `'hour'` | none for `round()`; `'nanosecond'` for `until`/`since` |
| `roundingIncrement` | Round to multiples of this many `smallestUnit`s | `1` |
| `roundingMode` | How to break the remainder | `'halfExpand'` for `round()`; `'trunc'` for `until`/`since` |
| `largestUnit` | Durations only: biggest unit in the result | depends on the type |
| `relativeTo` | Durations only: start point for calendar units | none |
If you only need smallestUnit, you can pass a string: time.round('minute') means the same as time.round({ smallestUnit: 'minute' }).
Rounding Plain times, date-times, and instants
const t = Temporal.PlainTime.from('14:37:45');
console.log(t.round('minute').toString()); // '14:38:00'
console.log(t.round({ smallestUnit: 'minute', roundingIncrement: 15 }).toString());
// '14:45:00'
console.log(
t.round({ smallestUnit: 'minute', roundingIncrement: 15, roundingMode: 'floor' }).toString()
); // '14:30:00'
const instant = Temporal.Instant.from('2024-03-15T12:34:56.789Z');
console.log(instant.round('second').toString()); // '2024-03-15T12:34:57Z'You need to know these rules for each type:
PlainDate,PlainYearMonth, andPlainMonthDayhave noround()method. They contain no time, so there is nothing below a day to round.PlainTimecan round up to'hour'.PlainDateTimeandZonedDateTimecan also round to'day', which moves the value to the nearest midnight.Instant.round()accepts units up to'hour'. It knows no calendar and no time zone, so it cannot round to a day.roundingIncrementmust divide evenly into the next larger unit. That means 15 minutes is valid and 7 minutes throws aRangeError. ForInstant, the increment must divide evenly into 24 hours.
Rounding ZonedDateTime to a day
ZonedDateTime rounds against the real length of the local day, which is not always 24 hours. On 10 March 2024 in New York, the clocks jumped from 02:00 to 03:00, so that day was only 23 hours long. Its midpoint therefore falls at 12:30 wall-clock time, not at noon.
const zdt = Temporal.ZonedDateTime.from('2024-03-10T13:00[America/New_York]');
console.log(zdt.round('day').toString());
// '2024-03-11T00:00:00-04:00[America/New_York]'13:00 falls after the 12:30 midpoint, so the value rounds forward to the next midnight. A PlainDateTime with the same fields knows nothing about the time change and would use noon as the midpoint.
Rounding modes
Temporal uses the same nine rounding modes as Intl.NumberFormat. The table shows each mode applied to 2.5 hours and to −2.5 hours, rounded to whole hours:
| Mode | 2.5 h | −2.5 h | Rule |
|---|---|---|---|
| `ceil` | 3 | −2 | Toward positive infinity |
| `floor` | 2 | −3 | Toward negative infinity |
| `expand` | 3 | −3 | Away from zero |
| `trunc` | 2 | −2 | Toward zero |
| `halfCeil` | 3 | −2 | Nearest; ties toward +∞ |
| `halfFloor` | 2 | −3 | Nearest; ties toward −∞ |
| `halfExpand` | 3 | −3 | Nearest; ties away from zero |
| `halfTrunc` | 2 | −2 | Nearest; ties toward zero |
| `halfEven` | 2 | −2 | Nearest; ties to the even number |
const d = Temporal.Duration.from({ minutes: 150 });
console.log(d.round({ smallestUnit: 'hour' }).toString()); // 'PT3H'
console.log(d.round({ smallestUnit: 'hour', roundingMode: 'halfEven' }).toString()); // 'PT2H'Rounding durations
Duration.prototype.round() needs at least one of smallestUnit or largestUnit. If you pass neither, it throws a RangeError. If you leave out largestUnit, it defaults to the larger of smallestUnit and the largest unit already present in the duration. This default can catch you out:
const worked = Temporal.Duration.from({ minutes: 61 });
const billed = worked.round({
smallestUnit: 'minute',
roundingIncrement: 15,
roundingMode: 'ceil',
});
console.log(billed.toString()); // 'PT75M' (largestUnit stayed 'minute')
const balanced = worked.round({
smallestUnit: 'minute',
roundingIncrement: 15,
roundingMode: 'ceil',
largestUnit: 'hour',
});
console.log(balanced.toString()); // 'PT1H15M'You can also call round() with only largestUnit and no smallestUnit. That balances the duration without dropping any precision, as in the earlier PT130M to PT2H10M example.
When relativeTo is required
A month can be 28 to 31 days long, and a year can be 365 or 366 days long. A duration that contains years, months, or weeks, or that asks for one of those as largestUnit or smallestUnit, can only be rounded from a known starting date. Without one, Temporal throws a RangeError. Without relativeTo, Temporal treats days as exactly 24 hours.
const span = Temporal.Duration.from({ days: 45 });
try {
span.round({ largestUnit: 'month' });
} catch (e) {
console.log(e instanceof RangeError); // true
}
console.log(
span.round({ largestUnit: 'month', relativeTo: Temporal.PlainDate.from('2024-01-01') }).toString()
); // 'P1M14D'
console.log(
span.round({ largestUnit: 'month', relativeTo: Temporal.PlainDate.from('2024-02-01') }).toString()
); // 'P1M16D'The same 45 days gives two different results because January has 31 days and February 2024 has 29. If you pass a ZonedDateTime as relativeTo, Temporal also uses the real lengths of days, including days that changed for daylight saving time.
Rounding inside until and since
until and since accept the rounding options directly, so you don't need a separate round() call. Their default mode is 'trunc', which differs from the 'halfExpand' default of round():
const start = Temporal.PlainDateTime.from('2024-03-15T09:00');
const end = Temporal.PlainDateTime.from('2024-03-15T17:47');
console.log(start.until(end, { smallestUnit: 'hour' }).toString()); // 'PT8H'
console.log(
start.until(end, { smallestUnit: 'hour', roundingMode: 'halfExpand' }).toString()
); // 'PT9H'The 'trunc' default suits countdowns and ages, where "8 hours" should mean "at least 8 full hours". For displays like "about 9 hours", set halfExpand yourself.
Common errors
- Calling
round()on aPlainDate. The method does not exist on that type. - Passing an increment that does not divide evenly into the next unit, such as 7 minutes or 25 seconds.
- Rounding a duration that contains months without
relativeTo. - Expecting
untilto round to the nearest value. It truncates unless you setroundingMode.
Exercise
A parking garage charges per started half hour. A car entered at 2024-06-01T08:10 and left at 2024-06-01T10:41 (PlainDateTime). Write one expression that returns a Duration of the billable time as hours and minutes.
Show answer
Temporal.PlainDateTime.from('2024-06-01T08:10').until(Temporal.PlainDateTime.from('2024-06-01T10:41'), { largestUnit: 'hour', smallestUnit: 'minute', roundingIncrement: 30, roundingMode: 'ceil' }) returns PT3H. The raw time is 2 hours 31 minutes, and ceil rounds that up to the next 30-minute block, which is 3 hours.
Exercise
Why does Temporal.Duration.from({ weeks: 1, hours: 5 }).round({ smallestUnit: 'day' }) throw, and how do you fix it?
Show answer
The duration contains weeks, which is a calendar unit, so rounding needs a reference point. Pass relativeTo, for example relativeTo: Temporal.PlainDate.from('2024-01-01'). The result is P1W because 5 hours is less than half a day and the default halfExpand mode rounds it down.