Temporal Arithmetic and Formatting

Updated · 7 min read
mediumES2026javascripttemporaldatesarithmetic

Temporal arithmetic is calculating with dates and times: adding a grace period, counting the days between two dates, comparing deadlines, rounding a duration. With Date, each of these needs careful hand-written math around milliseconds, month lengths and daylight saving. Temporal builds them in: add and subtract move a value, since and until measure the gap between two values, compare orders them, and round tidies the result. This lesson also covers formatting, converting between types, and moving existing Date code to Temporal.

In One Minute

  • date.add({ days: 30 }) and date.subtract({ months: 1 }) return new values.
  • Adding months clamps to the end of the month: January 31 plus one month is February 28.
  • a.until(b) and b.since(a) return a Duration; pass { largestUnit: "days" } (or "months"...) to choose the units.
  • Temporal.PlainDate.compare(a, b) returns -1, 0 or 1, ready for sort; a.equals(b) checks equality.
  • Format with toLocaleString("en-US", options); convert with methods like toPlainDate(), toZonedDateTime(zone) and toInstant().

Adding and Subtracting

add.js▶ Try it
const invoiced = Temporal.PlainDate.from("2026-01-31");
 
console.log(invoiced.add({ days: 30 }).toString());
console.log(invoiced.add({ months: 1 }).toString());
console.log(invoiced.add({ months: 1, days: 1 }).toString());
console.log(invoiced.subtract({ weeks: 2 }).toString());
console.log(invoiced.add({ years: 1 }).toString());
 
try {
  invoiced.add({ months: 1 }, { overflow: "reject" });
} catch (err) {
  console.log(err.name);
}
Output
2026-03-02
2026-02-28
2026-03-01
2026-01-17
2027-01-31
RangeError

Explanation: adding 30 days counts real days. Adding a month keeps the day number if it can, and clamps it to the last day of the month when it can't: there is no February 31, so the result is February 28. That is what people expect from "one month later". If you'd rather get an error, pass { overflow: "reject" }.

Measuring Differences: until and since

a.until(b) gives the duration from a to b; b.since(a) gives the same. The result's units default to the largest unit that makes sense for the type (days for PlainDate), and you can ask for others:

until.js▶ Try it
const enrolled = Temporal.PlainDate.from("2025-09-02");
const today = Temporal.PlainDate.from("2026-01-05");
 
console.log(enrolled.until(today).toString());
console.log(enrolled.until(today).days);
console.log(enrolled.until(today, { largestUnit: "months" }).toString());
console.log(today.since(enrolled, { largestUnit: "weeks" }).toString());
 
const due = Temporal.PlainDate.from("2026-01-20");
const daysLate = due.until(Temporal.PlainDate.from("2026-01-26")).days;
console.log(daysLate);
Output
P125D
125
P4M3D
P17W6D
6

Because PlainDate has no time zone and no time of day, the day count is always an exact calendar-day difference: no daylight saving surprises and no rounding, unlike dividing Date milliseconds by 86,400,000.

For times and moments, the same methods work with smaller units:

until-time.js▶ Try it
const start = Temporal.ZonedDateTime.from("2026-03-07T22:00[America/Chicago]");
const end = Temporal.ZonedDateTime.from("2026-03-08T08:00[America/Chicago]");
 
console.log(start.until(end).toString());
console.log(start.until(end, { largestUnit: "hours" }).hours);
Output
PT9H
9

Ten hours on the wall clock, but only 9 real hours passed, because clocks jumped forward at 2:00 AM on March 8. ZonedDateTime knows that.

Comparing and Sorting

Temporal values can't be compared with < or > (that throws a TypeError, on purpose, to stop accidental string comparison). Use the static compare and the equals method:

compare.js▶ Try it
const a = Temporal.PlainDate.from("2026-01-20");
const b = Temporal.PlainDate.from("2026-01-05");
 
console.log(Temporal.PlainDate.compare(a, b));
console.log(a.equals(Temporal.PlainDate.from("2026-01-20")));
 
const dues = ["2026-03-01", "2026-01-15", "2026-02-10"].map((s) => Temporal.PlainDate.from(s));
console.log(dues.toSorted(Temporal.PlainDate.compare).map(String));
 
try {
  console.log(a > b);
} catch (err) {
  console.log(err.name);
}
Output
1
true
['2026-01-15', '2026-02-10', '2026-03-01']
TypeError

compare returns exactly what sort needs, so Temporal.PlainDate.compare can be passed directly as the compare function.

Rounding

Durations and times can be rounded to a unit:

round.js▶ Try it
const worked = Temporal.Duration.from({ hours: 2, minutes: 47 });
console.log(worked.round({ smallestUnit: "hours" }).toString());
console.log(worked.round({ smallestUnit: "minutes", roundingIncrement: 15 }).toString());
 
const arrived = Temporal.PlainTime.from("09:07:43");
console.log(arrived.round({ smallestUnit: "minute" }).toString());
console.log(arrived.round({ smallestUnit: "minute", roundingIncrement: 15, roundingMode: "floor" }).toString());
Output
PT3H
PT2H45M
09:08:00
09:00:00

roundingIncrement: 15 rounds to quarter hours, and roundingMode chooses the direction ("halfExpand" by default, also "floor", "ceil", "trunc" and others).

Converting Between Types

FromToMethod
ZonedDateTimeInstant, PlainDate, PlainTime, PlainDateTimetoInstant(), toPlainDate(), toPlainTime(), toPlainDateTime()
InstantZonedDateTimetoZonedDateTimeISO(zone)
PlainDatePlainDateTimetoPlainDateTime(time)
PlainDateZonedDateTimetoZonedDateTime({ timeZone, plainTime })
PlainDateTimeZonedDateTimetoZonedDateTime(zone)
PlainDatePlainYearMonth, PlainMonthDaytoPlainYearMonth(), toPlainMonthDay()
DateInstantdate.toTemporalInstant() or Temporal.Instant.fromEpochMilliseconds(date.getTime())
InstantDatenew Date(instant.epochMilliseconds)
convert.js▶ Try it
const due = Temporal.PlainDate.from("2026-01-20");
const deadline = due.toZonedDateTime({ timeZone: "America/Chicago", plainTime: "17:00" });
 
console.log(deadline.toString());
console.log(deadline.toInstant().toString());
console.log(new Date(deadline.epochMilliseconds).toISOString());
console.log(due.toPlainYearMonth().toString());
Output
2026-01-20T17:00:00-06:00[America/Chicago]
2026-01-20T23:00:00Z
2026-01-20T23:00:00.000Z
2026-01

Formatting

Every Temporal type has toString() for ISO output and toLocaleString(locale, options) for people, using the same options as Intl.DateTimeFormat:

format.js▶ Try it
const zdt = Temporal.ZonedDateTime.from("2026-01-05T16:30[America/Chicago]");
const date = zdt.toPlainDate();
 
console.log(date.toLocaleString("en-US", { dateStyle: "full" }));
console.log(zdt.toLocaleString("en-US", { dateStyle: "medium", timeStyle: "short" }));
console.log(zdt.toLocaleString("en-US", { hour: "numeric", minute: "2-digit", timeZoneName: "short" }));
console.log(zdt.toString({ smallestUnit: "minute", timeZoneName: "never" }));
console.log(Temporal.Duration.from("PT2H30M").toLocaleString("en-US"));
Output
Monday, January 5, 2026
Jan 5, 2026, 4:30 PM
4:30 PM CST
2026-01-05T16:30-06:00
2 hr, 30 min

A ZonedDateTime formats in its own time zone, not the reader's, which is usually what you want for an event at a place. Duration.toLocaleString uses Intl.DurationFormat for readable lengths.

Migrating from Date

Date codeTemporal equivalent
new Date()Temporal.Now.instant() or Temporal.Now.zonedDateTimeISO(zone)
new Date(2026, 0, 5)Temporal.PlainDate.from({ year: 2026, month: 1, day: 5 })
d.setDate(d.getDate() + 30)d = d.add({ days: 30 })
(b - a) / 86_400_000a.until(b).days (for PlainDate)
a.getTime() === b.getTime()a.equals(b)
d.getMonth() + 1d.month
d.getDay() (0 = Sunday)d.dayOfWeek (1 = Monday, 7 = Sunday)
d.toISOString()instant.toString()
d.toLocaleDateString("en-US")plainDate.toLocaleString("en-US")

Migrate at the edges first: keep Date where a library or API requires it, convert to Temporal right away with toTemporalInstant(), do all your logic in Temporal, and convert back only when you must.

In Practice

The Fee Tracker builds a monthly payment schedule for a school year, on the 5th of each month, flags any due date that falls on a weekend, and formats each line for US readers:

schedule.js▶ Try it
function schedule(firstDue, months, amount) {
  const fmt = (d) => d.toLocaleString("en-US", { weekday: "short", month: "short", day: "numeric" });
  return Array.from({ length: months }, (_, i) => {
    const due = Temporal.PlainDate.from(firstDue).add({ months: i });
    const weekend = due.dayOfWeek >= 6 ? " (weekend: due next Monday)" : "";
    return `${fmt(due)}  $${amount}${weekend}`;
  });
}
 
schedule("2026-09-05", 4, 112.5).forEach((line) => console.log(line));
Output
Sat, Sep 5  $112.5 (weekend: due next Monday)
Mon, Oct 5  $112.5
Thu, Nov 5  $112.5
Sat, Dec 5  $112.5 (weekend: due next Monday)

Common Mistakes

MistakeWhat happensFix
a > b on Temporal valuesTypeErrorTemporal.PlainDate.compare(a, b) > 0
until(...).days with months in the resultdays is only the leftover partPass { largestUnit: "days" }
Adding days to an InstantRangeError (days need a zone)Use ZonedDateTime, or add { hours: 24 } on purpose
Expecting add to change the valueIt returns a new onedue = due.add(...)
Forgetting a zone when converting a plain value to a momentNo exact time exists without onetoZonedDateTime("America/Chicago")

Practice

Challenge: Write ageOn(birthday, date) that returns a person's age in whole years on a given date, using until with largestUnit: "years".

Show solution
age.js▶ Try it
function ageOn(birthday, date) {
  return Temporal.PlainDate.from(birthday).until(Temporal.PlainDate.from(date), { largestUnit: "years" }).years;
}
 
console.log(ageOn("2014-07-21", "2026-07-20"));
console.log(ageOn("2014-07-21", "2026-07-21"));
Output
11
12

Quick check: Temporal arithmetic

3 questions
1What is PlainDate.from("2026-01-31").add({ months: 1 })?
2How do you sort an array of PlainDate values?
3Why does start.until(end) between 10 PM and 8 AM across the March DST change give 9 hours for ZonedDateTime?

Key Takeaways

TaskCode
30 days laterd.add({ days: 30 })
Days betweena.until(b).days
Months betweena.until(b, { largestUnit: "months" })
Sortarr.toSorted(Temporal.PlainDate.compare)
Round to 15 minutest.round({ smallestUnit: "minute", roundingIncrement: 15 })
To Datenew Date(instant.epochMilliseconds)

Was this tutorial helpful?

Lesson 59 of 139