Deriving new times
So far, we've used dates to create an instant or a plain date-time (to various degrees of precision), store it in a variable, and display it to the user. The Temporal API can also derive new instants or plain date-times using arithmetic. We've already shown compare(), add()/subtract(), since()/until(), etc.; let's properly introduce the arithmetic methods on each Temporal object.
Instant |
ZonedDateTime |
PlainDateTime |
PlainDate |
PlainTime |
PlainYearMonth |
PlainMonthDay |
|
|---|---|---|---|---|---|---|---|
| Arithmetic | add()subtract()since()until() |
add()subtract()since()until() |
add()subtract()since()until() |
add()subtract()since()until() |
add()subtract()since()until() |
add()subtract()since()until() |
N/A |
| Rounding | round() |
round() |
round() |
N/A | round() |
N/A | N/A |
| Comparison | equals()Instant.compare() |
equals()ZonedDateTime.compare() |
equals()PlainDateTime.compare() |
equals()PlainDate.compare() |
equals()PlainTime.compare() |
equals()PlainYearMonth.compare() |
equals() |
Addition and subtraction involve another object, Temporal.Duration, representing the difference between two times. Its interface is relatively straightforward: it stores the number of years, months, days, etc., all the way to nanoseconds. It can be either positive or negative. You can combine it with other times or durations:
duration1.add(duration2),duration1.subtract(duration2): Calculate new durationstime.add(duration),time.subtract(duration): Calculate new times (we showZonedDateTimeexamples, but other time classes likePlainDateTimework similarly)time1.since(time2),time1.until(time2): Calculate new durations (we showZonedDateTimeexamples, but other time classes likePlainDateTimework similarly)
Note:
You can't do arithmetic with PlainMonthDay objects because they represent recurring dates, not a unique date/time.
For example, you can calculate the difference between two zoned date-times using since() and until(), which both give you Temporal.Duration objects. By default, the duration only uses units of hours or smaller:
const mdnCreation = Temporal.ZonedDateTime.from(
"2020-09-15T11:43:01-04:00[America/New_York]",
);
const bastilleFall = Temporal.ZonedDateTime.from(
"1789-07-14T17:00:00Z[Europe/Paris]",
);
const timeDiff = mdnCreation.since(bastilleFall);
console.log(
`mdn/content was created ${timeDiff.toLocaleString("en-US")} after the fall of the Bastille!`,
);
// mdn/content was created 2,026,414 hr, 43 min, 1 sec after the fall of the Bastille!
const timeDiff2 = bastilleFall.until(mdnCreation);
console.log(Temporal.Duration.compare(timeDiff, timeDiff2)); // 0 (equal)
Be aware that different Temporal classes have different restrictions on the durations they can process. For example, Instant has no calendar, so it cannot process calendar duration units like months; it also has no time zone, so it cannot process day units (because they may not be 24 hours long during offset transitions). PlainYearMonth is only accurate to whole months; durations less than a month are rounded off.
You can compare two times using the static compare() method, for example Temporal.ZonedDateTime.compare(a, b). This method returns a number with the same sign as a.epochNanoseconds - b.epochNanoseconds:
if (Temporal.ZonedDateTime.compare(mdnCreation, bastilleFall) > 0) {
console.log("mdn/content was created after the fall of the Bastille!");
} else {
console.log(
"What...? mdn/content is at least as old as the fall of the Bastille!",
);
}
Note:
PlainMonthDay objects are also not orderable.
Alternatively, you can use the equals() method to test if two objects store the same underlying data (this is stricter than just testing that they represent the same date/time). For ZonedDateTime, this requires their time zones and calendars to match; to compare only their instants, use Temporal.ZonedDateTime.compare(a, b) === 0.
if (mdnCreation.equals(bastilleFall)) {
// This won't execute, because the ZDTs both represent different instants
// and have different time zone IDs
console.log(
"mdn/content was created at the exact same instant as the fall of the Bastille!",
);
}
Finally, for objects carrying time components (Instant, ZonedDateTime, PlainDateTime, PlainTime), the round() method allows you to round off time units:
const mdnCreationHour = mdnCreation.round({ smallestUnit: "hours" });
console.log(
`mdn/content was created at approximately ${mdnCreationHour.toLocaleString("en-US")}`,
);
// mdn/content was created at approximately 9/15/2020, 12:00:00 PM EDT
All Temporal objects are immutable, so the same object always has the exact same underlying data. If you want to replace a single component or change the calendar or time zone, each class provides "with" methods to create new objects.
const mdnCreationNoon = mdnCreation.with({ hour: 12, minute: 0, second: 0 });
const mdnCreationChi = mdnCreation.withCalendar("chinese");
const mdnCreationParis = mdnCreation.withTimeZone("Europe/Paris");
Note:
If you can, prefer using arithmetic methods like add()/subtract() instead of manually setting components. This avoids dealing with overflows, time zone transitions, etc.
The Temporal.Now object
We've already shown Temporal.Now.timeZoneId(), which gives you the time zone ID of the current environment. You can also get the current time in various forms:
For example, you can get the current time in Paris, regardless of what time zone your system is in:
const parisNow = Temporal.Now.zonedDateTimeISO("Europe/Paris");