Sub topic 12
Handling Invalid Results: constrain vs reject
Some date operations can produce a value that does not exist. If you add one month to January 31, you get "February 31". If you build a time from user input, you might get "hour 25". In both cases Temporal has to choose between adjusting the value and failing. The overflow option tells it which one to do.
This chapter assumes you already know how to create values with from() and constructors, and how add, subtract, and with return new objects. Those topics are covered in earlier chapters. The examples assume Temporal is available, either natively or through the polyfill.
The two overflow modes
The overflow option accepts exactly two strings:
| Value | Behavior | Default? |
|---|---|---|
| `'constrain'` | Clamps each out-of-range field to the nearest valid value | Yes |
| `'reject'` | Throws a `RangeError` if any field is out of range | No |
Clamping works field by field. A day that is too large becomes the last day of the month. A month of 13 becomes 12. An hour of 25 becomes 23. Temporal never rolls the extra amount into the next unit. This is the main difference from legacy Date, which silently turns "February 31" into March 2 or 3.
const bag = { year: 2024, month: 2, day: 31 };
console.log(Temporal.PlainDate.from(bag).toString());
// '2024-02-29' (constrained to the last day of February)
try {
Temporal.PlainDate.from(bag, { overflow: 'reject' });
} catch (e) {
console.log(e instanceof RangeError); // true
}
// Compare with legacy Date, which rolls over into March
console.log(new Date(2024, 1, 31).getDate()); // 2Where the option applies
The overflow option works with any operation that combines fields and might land on a nonexistent value:
from()when given a property bag, for examplePlainDate.from({ ... }, { overflow })with(), for exampledate.with({ day: 31 }, { overflow })add()andsubtract()onPlainDate,PlainDateTime,PlainYearMonth, andZonedDateTime- The
toPlainDate()methods onPlainYearMonthandPlainMonthDaydon't take this option. They always constrain, soPlainMonthDayFebruary 29 becomes February 28 in a non-leap year.
const feb = Temporal.PlainDate.from('2023-02-10');
console.log(feb.with({ day: 31 }).toString()); // '2023-02-28'
console.log(feb.with({ month: 13 }).toString()); // '2023-12-10'
const t = Temporal.PlainTime.from({ hour: 25, minute: 75 });
console.log(t.toString()); // '23:59:00'
try {
feb.with({ day: 31 }, { overflow: 'reject' });
} catch (e) {
console.log(e.name); // 'RangeError'
}Where the option does not apply
Strings and constructors always behave as if overflow were 'reject'. An ISO 8601 string has to describe a real date. A constructor call has to receive valid fields.
try {
Temporal.PlainDate.from('2024-02-30', { overflow: 'constrain' });
} catch (e) {
console.log('string rejected:', e.name); // RangeError
}
try {
new Temporal.PlainDate(2024, 2, 30);
} catch (e) {
console.log('constructor rejected:', e.name); // RangeError
}Adding days, weeks, or time units never needs this option. Those amounts move along the timeline and always land on a real date. Only adding years and months can leave the day field past the end of the month.
Gotchas
Clamping is not reversible
Constraining loses information. After you clamp a date, subtracting the same amount does not bring you back to where you started.
const jan31 = Temporal.PlainDate.from('2024-01-31');
const back = jan31.add({ months: 1 }).subtract({ months: 1 });
console.log(back.toString()); // '2024-01-29', not '2024-01-31'For recurring events like "the last day of every month" or "the 31st, or the closest day to it", always compute from the original anchor date. Don't chain additions on the previous result: anchor.add({ months: n }) gives the right answer every time, and repeated add({ months: 1 }) drifts to the 29th and stays there.
Mixed units are checked partway through
When a duration mixes units, Temporal adds the years and months first and applies overflow to that intermediate date. Only then does it add the weeks and days. As a result, 'reject' can throw even when the final date would have been valid.
const jan31 = Temporal.PlainDate.from('2024-01-31');
console.log(jan31.add({ months: 1, days: 1 }).toString()); // '2024-03-01'
try {
jan31.add({ months: 1, days: 1 }, { overflow: 'reject' });
} catch (e) {
console.log('intermediate Feb 31 rejected'); // runs
}Zero and negative months and days always throw
Clamping applies to values above the valid range. A month or day of zero or less in a property bag throws a RangeError under both modes. Clamping will not turn a day: 0 into the 1st.
Typos in the option throw
Any value other than 'constrain' or 'reject' throws a RangeError. If you misspell the key itself, as in { overflo: 'reject' }, nothing throws. The option is ignored and the default 'constrain' applies without warning.
Choosing a mode
| Situation | Recommended mode | Reason |
|---|---|---|
| Validating form input or API payloads | `'reject'` | Invalid input should be reported, not silently changed |
| Billing cycles, "same day next month" | `'constrain'` | Clamping to the month's end is the expected business rule |
| Data imports where silent changes are dangerous | `'reject'` | A bad record should fail loudly |
| UI controls that step through months | `'constrain'` | Users expect to land on a valid day |
A common pattern is to reject at your trust boundaries and use the default inside your own business logic:
function parseUserDate(fields) {
try {
return { ok: true, value: Temporal.PlainDate.from(fields, { overflow: 'reject' }) };
} catch (e) {
if (e instanceof RangeError) return { ok: false, error: 'No such date' };
throw e;
}
}
console.log(parseUserDate({ year: 2023, month: 2, day: 29 }));
// { ok: false, error: 'No such date' }
console.log(parseUserDate({ year: 2024, month: 2, day: 29 }).value.toString());
// '2024-02-29'ZonedDateTime has two more options, disambiguation and offset, which handle clock times that are skipped or repeated during daylight saving changes. Those are a different problem from overflow, and a later chapter covers them.
Exercise
What does Temporal.PlainDate.from('2023-03-31').with({ month: 4 }).toString() return, and what happens if you pass { overflow: 'reject' } as the second argument to with()?
Show answer
It returns '2023-04-30' because April has 30 days and the default 'constrain' clamps day 31 to 30. With { overflow: 'reject' }, with() throws a RangeError.
Exercise
A subscription starts on 2024-01-31. Code computes each renewal as previous.add({ months: 1 }). What is the renewal date for April, and how should the code be written to renew on April 30?
Show answer
The chain gives Feb 29, then Mar 29, then Apr 29, because clamping to the 29th carries forward. Compute each renewal from the anchor date instead: start.add({ months: n }). With n = 3 this gives 2024-04-30.
Exercise
Why does Temporal.PlainDate.from('2024-02-30', { overflow: 'constrain' }) throw instead of returning 2024-02-29?
Show answer
The overflow option only applies to property bags and arithmetic. ISO strings must describe a valid date, so an invalid string always throws a RangeError no matter which overflow value you pass.