Skip to content
AnswerWell geo Documentation

Research · 7 min read · Answerwell

Temporal API: Plain Dates, Zoned Events, Durations, and Calendars

How to use JavaScript Temporal for calendar dates, time zones, elapsed time, high-precision logs, and non-Gregorian calendars without legacy Date pitfalls.

This page summarizes Chrome Modern Web Guidance on the JavaScript Temporal API: choosing the right type for birthdates versus meeting times, computing elapsed or remaining time with DST-safe math, formatting spans for users, and handling nanosecond log timestamps and alternate calendars. The legacy Date object stores only epoch milliseconds in the proleptic Gregorian calendar, which makes partial dates, time-zone wall times, and sub-millisecond ordering easy to get wrong.

Temporal types: which object models your data?

Section titled “Temporal types: which object models your data?”

Temporal splits “what the calendar says” from “which instant on the UTC timeline” and from “wall clock in a named region.” Pick the narrowest type that matches what you store.

Type What it models Typical use
Temporal.PlainDate Full calendar date (year, month, day) Birthdates, billing dates
Temporal.PlainTime Wall-clock time Daily alarms, store hours
Temporal.PlainDateTime Date + time without a zone Floating local schedules
Temporal.PlainMonthDay Month and day without year Annual holidays, birthdays
Temporal.PlainYearMonth Year and month without day Card expiry, billing periods
Temporal.ZonedDateTime Date-time in an IANA time zone Subscriptions, SLA windows, global meetings
Temporal.Instant Exact UTC timeline point (nanosecond precision) Logs, audit timelines
Temporal.Duration Elapsed time between events Countdowns, intervals

Recording chronological data that should remain identical regardless of the viewer’s location—such as birthdates, daily alarms, credit card expirations, or monthly billing cycles—has historically been error-prone with the legacy Date object.

— Chrome, Capturing Location-Agnostic Data and Partial Dates with Temporal

Use Plain types when the value must read the same in every time zone. Use ZonedDateTime when the event is tied to a place (renewal at midnight in America/New_York). Use Instant when the source already recorded an unambiguous UTC timestamp string.

PlainDate and partial dates: how to avoid time zone drift

Section titled “PlainDate and partial dates: how to avoid time zone drift”

Parse full dates with Temporal.PlainDate.from('1990-01-01') and times with Temporal.PlainTime.from('09:00'). Combine with methods such as birthdate.toPlainDateTime(reminderTime) instead of building ISO strings with template literals.

For card-style expiry, use Temporal.PlainYearMonth so arbitrary “day 31” placeholders never enter arithmetic. For recurring annual dates, use Temporal.PlainMonthDay and convert to PlainDate with .toPlainDate({ year }) before adding months, because February length depends on the year.

When constructing PlainMonthDay or PlainYearMonth from object literals, pass calendar: 'iso8601' explicitly when needed. Compare Plain values with .equals() or Temporal.PlainDate.compare, not string comparison.

Legacy Date interop: why conversion must be explicit

Section titled “Legacy Date interop: why conversion must be explicit”

A Date is an instant, not a calendar date. Storing "1990-01-01" as Date and reading it west of UTC can show the previous calendar day. Convert deliberately:

  • PlainDate → Date: birthdate.toZonedDateTime('UTC').toInstant() then new Date(instant.epochMilliseconds) (document which zone you chose).
  • Date → PlainDate: Temporal.Instant.fromEpochMilliseconds(legacyDate.getTime()).toZonedDateTimeISO('America/New_York').toPlainDate() — the zone you pick defines the recovered calendar fields.

For meetings or renewals bound to a city, create Temporal.ZonedDateTime with an IANA name such as America/New_York, never a fixed offset like “UTC-5.”

The Temporal API provides Temporal.ZonedDateTime to represent a date and time in a specific time zone, handling DST transitions automatically and predictably.

— Chrome, Coordinating Global Events with Temporal

During spring-forward, some local times do not exist; during fall-back, some times are ambiguous. Control that with disambiguation:

  • disambiguation: 'reject' — throws RangeError when the time is invalid or ambiguous; use this to detect scheduling conflicts and warn users.
  • disambiguation: 'compatible' (default) — resolves to a valid local time when possible.

Convert for other attendees with .withTimeZone('Asia/Tokyo') on the immutable zoned value; display with .toLocaleString() rather than manual zero-padding.

Build zoned endpoints for differentials the same way: chain Temporal.PlainDate.from(dateStr).toPlainDateTime(timeStr).toZonedDateTime(tz) instead of `${dateStr}T${timeStr}`.

Obtain “now” in the event’s zone with Temporal.Now.zonedDateTimeISO(timeZone) when it differs from the system default.

Event differentials: .since(), .until(), and DurationFormat

Section titled “Event differentials: .since(), .until(), and DurationFormat”

To show trial time active or time remaining, pair Temporal.ZonedDateTime with Temporal.Duration and Intl.DurationFormat.

The Temporal API pairs Temporal.ZonedDateTime with Temporal.Duration and Intl.DurationFormat to provide DST-safe time differentials, configurable unit balancing, calendar-aware duration comparisons, and localized formatting.

— Chrome, Calculating Event Differentials and Formatting Durations with Temporal

  • now.since(start, options) — elapsed since a past zoned time.
  • now.until(end, options) — remaining until a future zoned time.

Unit balancing: zoned differences default to largestUnit: 'hour' because days are not a fixed length across DST. Pass largestUnit: 'day', 'month', or 'year' when you want human-scale breakdowns. Set smallestUnit (for example 'minute') to round away sub-minute noise in UI copy.

Rebalance standalone durations with Temporal.Duration.from({ minutes: 90 }).round({ largestUnit: 'hour' }). When comparing two durations that include calendar units or cross DST, use Temporal.Duration.compare(d1, d2, { relativeTo }) with a PlainDate or ZonedDateTime anchor.

Formatting:

  • Users: duration.toLocaleString(locale, { style: 'long' | 'short' | 'narrow' | 'digital' }) or new Intl.DurationFormat(...).
  • APIs and <time datetime="...">: duration.toString() for ISO 8601 duration strings (for example PT1H30M), not user-facing text.

Check expiry with timeRemaining.sign < 0. Temporal objects are immutable; .add(), .round(), and .with() return new instances.

Temporal.Instant: sort and diff high-precision log timestamps

Section titled “Temporal.Instant: sort and diff high-precision log timestamps”

Server and database logs may include fractional seconds beyond milliseconds. new Date(isoString) truncates to milliseconds, so distinct events in the same millisecond can collide when sorted.

Temporal.Instant represents an exact point on the UTC timeline with nanosecond precision and no attached time zone.

— Chrome, Sorting High-Precision Timestamps with Temporal.Instant

Parse preserved strings with Temporal.Instant.from(isoString). Sort with Temporal.Instant.compare(a, b). Measure gaps with instant.since(previousInstant) and format gaps with duration.toLocaleString().

Do not use duration.total('nanoseconds') for long spans in display logic—values beyond ~104 days exceed Number.MAX_SAFE_INTEGER. Keep intervals as Temporal.Duration. To show local wall time for an instant, use instant.toZonedDateTimeISO(timeZone).

Non-Gregorian calendars: withCalendar and monthCode

Section titled “Non-Gregorian calendars: withCalendar and monthCode”

Temporal can associate calendar identifiers (Islamic, Hebrew, Chinese, Japanese, and others) with date objects so arithmetic and formatting follow that system’s rules.

Implementation essentials from Supporting Global Calendar Systems with Temporal:

  • Switch calendars with .withCalendar(calendarId) on a PlainDate.
  • In lunisolar calendars with leap months, identify months with monthCode, not only numeric month.
  • Loop months using monthsInYear and daysInMonth, not fixed 12 or 31.
  • Compare within a calendar using Temporal.PlainDate.compare.
  • Check support with Intl.supportedValuesOf('calendar') when available.
  • Format with toLocaleString() (include era for era-based calendars).

Some religious calendars depend on observation; Temporal follows the environment’s Intl calculations—verify critical dates with domain expertise when required.

Recurring billing and overflow on PlainDate

Section titled “Recurring billing and overflow on PlainDate”

Monthly intervals on PlainDate use .add({ months: 1 }). Default overflow: 'constrain' clamps Jan 31 forward to the last valid February day; overflow: 'reject' throws when the target day does not exist. Choose reject when invalid billing dates must surface as errors instead of silent clamping.

Native Temporal is not universal yet. Chrome’s guides recommend feature detection and loading temporal-polyfill (~15 KB min+gzip). Importing the polyfill does not assign globalThis.Temporal automatically—assign it if your code expects a global.

(async () => {
if (typeof Temporal === 'undefined') {
const module = await import('https://esm.sh/temporal-polyfill');
globalThis.Temporal = module.Temporal;
Date.prototype.toTemporalInstant = module.toTemporalInstant;
}
initializeApp();
})();

Intl (including duration and date formatting) is also available in runtimes such as Cloudflare Workers web standards for locale-aware output alongside Temporal.

  • Using Date arithmetic for zoned or calendar-month differentials instead of .since() / .until() on ZonedDateTime.
  • Storing birthdates as Date midnight UTC and wondering why UI shows the wrong day.
  • Using PlainDateTime for global meetings that must survive DST.
  • Formatting durations by concatenating ${years}y ${months}m instead of Intl.DurationFormat.
  • Parsing nanosecond log lines with Date.parse and getting unstable sort order.
  • Mutating Temporal instances in place (they always return new values).
  • Identifying time zones by fixed UTC offsets instead of IANA names.
  1. In the browser console on your deployment, run typeof Temporal !== 'undefined' and exercise the types your feature uses (PlainDate.from, ZonedDateTime.from, or Instant.from on a sample ISO string from your API).

  2. For user-visible countdowns, log both duration.toLocaleString(undefined, { style: 'long' }) and duration.toString() and confirm only the locale string appears in the UI.

  3. Schedule a test ZonedDateTime on a known DST boundary in your target IANA zone with disambiguation: 'reject' and confirm your UI handles RangeError when users pick invalid local times.

  4. Sort a small array of server timestamps that share the same millisecond using Temporal.Instant.compare and confirm order matches the raw string precision.

  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact sentence you are asking about, and we will correct or clarify it.