Sub topic 11
Adding, Subtracting, and Replacing Fields
This chapter assumes you have read the earlier chapters on immutability, the Plain types, and creating values with from(). All examples assume Temporal is in scope, either as the native global or through the polyfill set up earlier.
Temporal gives you three tools for changing a value. Each returns a new object and leaves the original unchanged:
| Method | What it does | Typical use |
|---|---|---|
| `add(duration)` | Moves forward by a duration | "Due in 30 days" |
| `subtract(duration)` | Moves backward by a duration | "Reminder one week before" |
| `with(fields)` | Replaces chosen fields and keeps the rest | "Same date, but the 1st of the month" |
add and subtract
What a duration argument can be
add and subtract accept anything that can be turned into a Temporal.Duration: a Duration object, a property bag, or an ISO 8601 duration string.
const date = Temporal.PlainDate.from('2024-03-15');
console.log(date.add({ weeks: 2 }).toString()); // '2024-03-29'
console.log(date.add('P1M2D').toString()); // '2024-04-17'
console.log(date.add(Temporal.Duration.from({ days: 10 })).toString()); // '2024-03-25'
console.log(date.subtract({ years: 1 }).toString()); // '2023-03-15'
console.log(date.subtract({ months: -1 }).toString()); // '2024-04-15'Subtracting a negative duration is the same as adding a positive one. A single duration cannot mix signs, though. { months: 1, days: -1 } throws a RangeError, both in Duration.from and when passed straight to add. To express "one month minus a day", make two calls.
Units are applied largest first
When a duration has several units, Temporal applies years first, then months, then weeks, then days. Clamping to a valid date happens after each step. This order can change the result:
const jan31 = Temporal.PlainDate.from('2024-01-31');
console.log(jan31.add({ months: 1, days: 1 }).toString()); // '2024-03-01'
console.log(jan31.add({ days: 1 }).add({ months: 1 }).toString()); // '2024-03-01'
console.log(jan31.add({ months: 1 }).add({ days: 1 }).toString()); // '2024-03-01'
const jan30 = Temporal.PlainDate.from('2024-01-30');
console.log(jan30.add({ days: 1 }).add({ months: 1 }).toString()); // '2024-02-29'
console.log(jan30.add({ months: 1 }).add({ days: 1 }).toString()); // '2024-03-01'The last two lines start from the same date and use the same units, but chaining them in a different order gives a different answer. If the order matters to your business rule, write it out explicitly as separate calls.
Calendar arithmetic is not reversible
Month and year arithmetic clamps to the end of the month (the default constrain behavior, covered in the next chapter). Clamping throws information away, so subtracting what you added does not always bring you back:
const jan31 = Temporal.PlainDate.from('2024-01-31');
const back = jan31.add({ months: 1 }).subtract({ months: 1 });
console.log(back.toString()); // '2024-01-29'
console.log(back.equals(jan31)); // falseWhich units each type accepts
Every type does arithmetic in the units that make sense for it:
PlainDateworks in years, months, weeks, and days.PlainTimeworks in hours and smaller units, and wraps around midnight without carrying over a day.PlainDateTimeandZonedDateTimeaccept every unit.Instanthas no calendar, so it accepts hours and smaller units only. Passing days, weeks, months, or years throws aRangeError.
const t = Temporal.PlainTime.from('23:30');
console.log(t.add({ hours: 1 }).toString()); // '00:30:00'
const dt = Temporal.PlainDateTime.from('2024-03-15T09:00');
console.log(dt.add({ hours: 20 }).toString()); // '2024-03-16T05:00:00'
const instant = Temporal.Instant.from('2024-03-15T12:00:00Z');
console.log(instant.add({ hours: 36 }).toString()); // '2024-03-17T00:00:00Z'
try {
instant.add({ days: 1 });
} catch (e) {
console.log(e instanceof RangeError); // true
}Instant rejects days because the length of a day depends on the time zone. To add calendar days to an exact moment, convert it to a ZonedDateTime first. On a ZonedDateTime, { days: 1 } keeps the wall-clock time and { hours: 24 } adds exact elapsed time. The two differ across a daylight saving change, which a later chapter covers in detail.
Replacing fields with with
with takes a property bag of fields to change and copies every other field from the original. It does not do arithmetic. It sets values.
const date = Temporal.PlainDate.from('2024-03-15');
console.log(date.with({ day: 1 }).toString()); // '2024-03-01'
console.log(date.with({ day: date.daysInMonth }).toString()); // '2024-03-31'
console.log(date.with({ year: 2025, month: 1 }).toString()); // '2025-01-15'
// Start of next month: replace, then add
console.log(date.with({ day: 1 }).add({ months: 1 }).toString()); // '2024-04-01'
// Invalid combinations are clamped by default
const feb = Temporal.PlainDate.from('2024-02-10');
console.log(feb.with({ day: 31 }).toString()); // '2024-02-29'daysInMonth, daysInYear, and inLeapYear are computed properties you can read and then pass to with. Using them avoids hard-coding month lengths.
Common with mistakes
- An empty or unrecognized bag.
date.with({})ordate.with({ days: 3 })throws aTypeError. The field isday(singular).daysis a duration unit. - Passing a Temporal object.
date.with(otherDate)throws aTypeError. Usefromor read the fields you need. - Changing calendar or time zone.
withcannot do this. UsewithCalendar()on dates, andwithTimeZone()onZonedDateTime. - Confusing with and add.
with({ month: 4 })sets the month to April.add({ months: 4 })moves four months ahead.
Replacing whole parts
Date-time types have helpers that swap a complete date or time part in one call:
const dt = Temporal.PlainDateTime.from('2024-03-15T09:00');
console.log(dt.withPlainTime('17:30').toString()); // '2024-03-15T17:30:00'
console.log(dt.withPlainTime().toString()); // '2024-03-15T00:00:00'
const zdt = Temporal.ZonedDateTime.from('2024-03-15T09:00[Europe/Paris]');
console.log(zdt.withPlainTime('18:00').toString());
// '2024-03-15T18:00:00+01:00[Europe/Paris]'When you call withPlainTime() with no argument, it sets the time to midnight. For a ZonedDateTime, startOfDay() is safer, because in some zones midnight does not exist on the day clocks change.
Choosing the right tool
| Requirement | Use |
|---|---|
| Relative move ("3 days later") | `add` / `subtract` |
| Absolute field ("on the 1st") | `with` |
| Same day, different time | `withPlainTime` |
| End of month | `with({ day: d.daysInMonth })` |
| Exact elapsed time on a moment | `Instant.add({ hours, minutes, ... })` |
Exercise
What does Temporal.PlainDate.from('2023-01-31').add({ months: 1 }).subtract({ months: 1 }).toString() print, and why is it not '2023-01-31'?
Show answer
It prints '2023-01-28'. Adding one month to January 31 in a non-leap year clamps to '2023-02-28'. Subtracting one month from February 28 gives January 28. The clamp threw away the original day number.
Exercise
Write an expression that returns the last day of the month before a given PlainDate d, without hard-coding month lengths.
Show answer
const prev = d.subtract({ months: 1 }); prev.with({ day: prev.daysInMonth }). You can also write d.with({ day: 1 }).subtract({ days: 1 }), which works because the day before the 1st is always the last day of the previous month.
Exercise
Why does Temporal.Instant.from('2024-03-15T12:00:00Z').add({ days: 1 }) throw, and how would you add one calendar day in New York time?
Show answer
An Instant has no time zone or calendar, so it cannot know how long a day is, and Temporal throws a RangeError instead of guessing. Convert first: instant.toZonedDateTimeISO('America/New_York').add({ days: 1 }). Call .toInstant() on the result if you need an Instant back.