Sub topic 11
Handling Invalid Results: constrain vs reject
This chapter assumes you already know how to create PlainDate values and how to call add, subtract, and with on them. Code samples use the Temporal fallback setup from the runtime support chapter.
When arithmetic lands on a day that doesn't exist
Some calculations produce dates that are not on the calendar. January 31 plus one month would be February 31. Temporal does not quietly roll that over into March, which is what legacy Date does. Instead it asks you to choose a policy through the overflow option:
'constrain'is the default. It clamps the value to the nearest valid one, which here is the last day of February.'reject'throws aRangeError, so your code has to deal with the problem explicitly.
import { Temporal as TemporalPolyfill } from '@js-temporal/polyfill';
const Temporal = globalThis.Temporal ?? TemporalPolyfill;
const jan31 = Temporal.PlainDate.from('2024-01-31');
console.log(jan31.add({ months: 1 }).toString()); // '2024-02-29'
console.log(jan31.toString()); // '2024-01-31' (unchanged)
try {
jan31.add({ months: 1 }, { overflow: 'reject' });
} catch (e) {
console.log(e instanceof RangeError); // true
}The same option works with with and with from when you pass a property bag:
import { Temporal as TemporalPolyfill } from '@js-temporal/polyfill';
const Temporal = globalThis.Temporal ?? TemporalPolyfill;
const feb = Temporal.PlainDate.from('2024-02-10');
console.log(feb.with({ day: 31 }).toString()); // '2024-02-29'
const bag = { year: 2024, month: 2, day: 30 };
console.log(Temporal.PlainDate.from(bag).toString()); // '2024-02-29'
// Temporal.PlainDate.from(bag, { overflow: 'reject' }) -> RangeErrorISO strings are a special case. Temporal.PlainDate.from('2024-02-30') always throws, whatever the overflow setting, because the string itself is malformed.
Working with Temporal.Duration
A Duration is a length of time with no starting point, such as "1 hour 30 minutes". You can build one from a property bag or an ISO 8601 duration string like 'PT1H30M'.
import { Temporal as TemporalPolyfill } from '@js-temporal/polyfill';
const Temporal = globalThis.Temporal ?? TemporalPolyfill;
const meeting = Temporal.Duration.from({ hours: 1, minutes: 30 });
console.log(meeting.toString()); // 'PT1H30M'
console.log(meeting.total({ unit: 'minute' })); // 90
const long = Temporal.Duration.from({ minutes: 130 });
console.log(long.toString()); // 'PT130M'
console.log(long.round({ largestUnit: 'hour' }).toString()); // 'PT2H10M'A duration keeps the fields exactly as you gave them, so { minutes: 130 } stays as 130 minutes. Use round with largestUnit to balance it into larger units, and use total when you need a single number.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Mixing signs, e.g. `{ hours: 1, minutes: -30 }` | `RangeError` | Use one sign for every field. Call `negated()` to flip it |
| Calling `total` or `round` on a duration with months or years | `RangeError`, because months vary in length | Pass `relativeTo`, e.g. `{ unit: 'day', relativeTo: '2024-02-01' }` |
| Comparing durations with `<` | `TypeError` | Use `Temporal.Duration.compare` |
import { Temporal as TemporalPolyfill } from '@js-temporal/polyfill';
const Temporal = globalThis.Temporal ?? TemporalPolyfill;
const oneMonth = Temporal.Duration.from({ months: 1 });
console.log(oneMonth.total({ unit: 'day', relativeTo: '2024-02-01' })); // 29
console.log(oneMonth.total({ unit: 'day', relativeTo: '2024-03-01' })); // 31Exercise
What does Temporal.PlainDate.from('2023-03-31').subtract({ months: 1 }).toString() return, and what changes if you pass { overflow: 'reject' }?
Show answer
It returns '2023-02-28', because February 2023 has no 31st and the default 'constrain' clamps to the last valid day. With { overflow: 'reject' } the call throws a RangeError.
Exercise
How would you turn Temporal.Duration.from({ seconds: 5400 }) into a duration expressed in hours and minutes, and how would you get it as a number of hours?
Show answer
Call duration.round({ largestUnit: 'hour' }) to get 'PT1H30M'. Call duration.total({ unit: 'hour' }) to get 1.5.