How to use the JavaScript Temporal API for dates and time zones

By

Updated

Tagged: JavaScript

Learn JavaScript Temporal through dates, instants, time zones, DST-safe arithmetic, durations, formatting, storage, testing, and real application workflows.

JavaScript has had one date and time object since 1995: Date.

It tries to represent too many different ideas with a single mutable value. A birthday, a local appointment, a UTC timestamp, and the current time all become a Date, and that creates ambiguity.

Does 2026-08-10 mean midnight in Copenhagen, midnight in UTC, or a calendar date with no time zone at all? Is “add one day” the same as “add 24 hours” when daylight saving time changes? Should changing a month mutate a value another function is still using?

The Temporal API fixes that model.

Temporal gives each kind of date and time its own immutable type, so you choose what a value means before you manipulate it.

In this tutorial, we’ll learn that model, walk through every main type, handle time zones and daylight saving transitions, and build the date workflows I use in real projects. Here’s a quick look at how Temporal reads in practice:

Instantexact pointZonedDateTimepoint + time zonePlainDatecalendar datePlainTimewall-clock timePlainDateTimedate + timeDurationamount of time

Why Date is difficult

Date stores a single number: milliseconds since the Unix epoch. It’s widely implemented and accepted by almost every JavaScript library.

The trouble starts when we ask it to act like several different types at once.

Months are zero-based

This creates January 15:

const date = new Date(2026, 0, 15)

The month is 0 while the day is 15, and that convention has caused bugs for decades.

Values are mutable

This changes the original object:

const launch = new Date('2026-08-10T09:00:00Z')
const reminder = launch

reminder.setDate(reminder.getDate() - 1)

launch changed too because both variables reference the same object.

Parsing can hide a time zone conversion

These strings look related, but they don’t mean the same thing:

new Date('2026-08-10')
new Date('2026-08-10T00:00:00')
new Date('2026-08-10T00:00:00Z')

The first parses as UTC, the second uses the system’s local time zone, and the third explicitly specifies UTC.

A time zone is not part of the value

A Date only represents an instant. Local getters and formatters project it through whatever time zone the environment or formatter supplies, so it can’t represent “09:00 in Europe/Rome, using that zone’s future daylight-saving rules” as one value.

Calendar arithmetic and elapsed time get mixed

Tomorrow at 09:00 is a calendar operation, while exactly 24 hours from now is an elapsed-time operation. Temporal keeps them separate because their results can differ across a daylight-saving transition.

Temporal reached Stage 4

Temporal reached TC39 Stage 4 in 2025, and the current specification draft is being integrated into ECMAScript.

The API provides:

  • immutable date and time objects
  • nanosecond precision
  • first-class IANA time zones
  • calendar-aware arithmetic
  • explicit parsing and serialization
  • types for dates, times, instants, durations, year/month, and month/day values

Existing Date code will keep working because Temporal doesn’t remove it.

Start by choosing the meaning

Before you write code, ask what the value represents.

MeaningTemporal typeExample
Exact point on the timelineInstantpayment received at a server
Exact point shown in a named zoneZonedDateTimelivestream starts in Rome
Calendar date without a zonePlainDatebirthday or due date
Wall-clock time without a datePlainTimeshop opens at 09:00
Date and wall-clock time without a zonePlainDateTimeform input awaiting a zone
Year and monthPlainYearMonthcredit-card expiry month
Recurring month and dayPlainMonthDayannual birthday
Amount of time or calendar unitsDuration2 months and 3 days

Most Temporal mistakes start by picking a type with the wrong meaning.

Temporal is a namespace

Temporal is a global object, similar to Math. You don’t construct it:

Temporal() // wrong
new Temporal() // wrong

Instead, you use the classes and helpers it contains:

const date = Temporal.PlainDate.from('2026-08-10')
const now = Temporal.Now.instant()

Temporal values are immutable

Every operation returns a new value:

const launch = Temporal.PlainDate.from('2026-08-10')
const reminder = launch.subtract({ days: 1 })

launch.toString() // '2026-08-10'
reminder.toString() // '2026-08-09'

The original date can’t change behind your back, which makes values safer to pass between functions, store in state, and reuse in tests.

Temporal.Now

Temporal.Now reads the host system clock.

Get the current exact instant:

const now = Temporal.Now.instant()

Get today’s ISO date in a specific time zone:

const today = Temporal.Now.plainDateISO('Europe/Copenhagen')

Get the current zoned date and time:

const localNow = Temporal.Now.zonedDateTimeISO(
  'Europe/Copenhagen',
)

Passing the time zone matters on servers, since a server might run in UTC while your product’s business day follows Europe/Rome.

Try not to scatter calls to Temporal.Now through your business logic. Pass the current value into functions instead so tests can control it.

Temporal.PlainDate

A PlainDate holds a year, month, and day, with no clock time and no time zone.

Use it for birthdays, release dates, invoice dates, and calendar deadlines:

const launch = Temporal.PlainDate.from('2026-08-14')

launch.year // 2026
launch.month // 8
launch.day // 14
launch.dayOfWeek // 5

Months are one-based, so August is 8.

You can also create a date from fields:

const launch = Temporal.PlainDate.from({
  year: 2026,
  month: 8,
  day: 14,
})

Calendar arithmetic

Adding calendar units is straightforward:

const start = Temporal.PlainDate.from('2026-08-14')
const nextWeek = start.add({ weeks: 1 })
const previousMonth = start.subtract({ months: 1 })

Temporal handles different month lengths and leap years.

By default, invalid results get constrained. Adding one month to January 31 gives you the last valid day of February:

const date = Temporal.PlainDate.from('2027-01-31')

date.add({ months: 1 }).toString() // '2027-02-28'

Ask Temporal to reject overflow when silent adjustment isn’t acceptable:

Temporal.PlainDate.from(
  { year: 2027, month: 2, day: 31 },
  { overflow: 'reject' },
)

Temporal throws a RangeError for that date.

Temporal.PlainTime

A PlainTime is a wall-clock time without a date or time zone:

const opening = Temporal.PlainTime.from('09:30')

opening.hour // 9
opening.minute // 30

Use it for values like “the shop opens at 09:30.” Don’t use it for “the job ran at 09:30,” because that event happened on a date and timeline.

Temporal.PlainDateTime

A PlainDateTime combines calendar and wall-clock fields without choosing a time zone:

const input = Temporal.PlainDateTime.from(
  '2026-10-25T02:30:00',
)

This matches what you’d receive from a datetime-local form control.

It isn’t an exact moment yet. Different time zones can map those fields to different instants, and during a daylight-saving transition, a single zone can even map them to zero or two possible instants.

Choose a time zone before scheduling real work:

const scheduled = input.toZonedDateTime(
  'Europe/Rome',
)

Temporal.Instant

An Instant is one exact point on the UTC timeline. Use it for server timestamps, audit events, payment times, token expiration, and log entries:

const receivedAt = Temporal.Instant.from(
  '2026-08-10T08:15:30.123456789Z',
)

The Z is required because an instant needs an offset.

You can create one from Unix time:

const instant = Temporal.Instant.fromEpochMilliseconds(
  1786349730123,
)

Read epoch values when an external API needs them:

instant.epochMilliseconds
instant.epochNanoseconds

An instant has no display time zone, so convert it when you need to show it to a user:

const rome = instant.toZonedDateTimeISO('Europe/Rome')

Temporal.ZonedDateTime

A ZonedDateTime combines:

  • an exact instant
  • an IANA time-zone identifier
  • a calendar

Use this type for events that happen at a real moment and still need to follow local clock rules:

const workshop = Temporal.ZonedDateTime.from(
  '2026-08-14T09:00:00+02:00[Europe/Rome]',
)

The string includes both the numeric offset and the named time zone. The offset pins down this exact instant, while the zone provides the rule set needed for future and past calculations.

You can convert the same instant for another audience:

const newYork = workshop.withTimeZone('America/New_York')

workshop.hour // 9
newYork.hour // 3

The wall-clock fields change for the new zone while the underlying instant stays the same:

One instantEurope/Rome09:00America/New_York03:00Asia/Tokyo16:00

A named time zone is not an offset

+02:00 is an offset, while Europe/Rome is a time zone.

An offset tells you how far local time is from UTC at one moment, whereas a zone holds the rules that determine offsets across past and future transitions. Rome uses +01:00 in winter and +02:00 in summer, and a fixed offset can’t model that change.

Store a named zone whenever future local time matters.

Daylight saving gaps and repeated times

When clocks move forward, some local times don’t exist. When clocks move backward, some local times happen twice.

Consider 02:30 during a transition. Temporal lets you choose a disambiguation policy:

const local = Temporal.PlainDateTime.from(
  '2026-10-25T02:30:00',
)

const earlier = local.toZonedDateTime(
  'Europe/Rome',
  { disambiguation: 'earlier' },
)

const later = local.toZonedDateTime(
  'Europe/Rome',
  { disambiguation: 'later' },
)

The options are:

  • compatible, the default behavior designed for legacy compatibility
  • earlier, choose the earlier possible instant
  • later, choose the later possible instant
  • reject, throw when the local time is ambiguous or missing

For financial cutoffs, bookings, and scheduled jobs, I prefer reject so the app can ask the user to choose instead of silently guessing:

onezero: DST gaptwo: repeated timeLocal date and timeHow many matchinginstants?Use itShift or rejectEarlier, later, orreject

One day is not always 24 hours

This is one of the most important things Temporal gets right. Start before a daylight-saving change:

const start = Temporal.ZonedDateTime.from(
  '2026-03-28T12:00:00+01:00[Europe/Rome]',
)

Add one calendar day:

const tomorrow = start.add({ days: 1 })

You get noon on the next calendar day. If the clock moved forward overnight, only 23 elapsed hours passed.

Add 24 exact hours instead:

const later = start.add({ hours: 24 })

That preserves elapsed time, so the local clock can show 13:00.

Use days for calendar schedules, and use hours, minutes, seconds, or instants when you care about elapsed time.

Temporal.Duration

A Duration represents an amount of time, like “two months and three days” or “90 minutes”:

const trial = Temporal.Duration.from({ days: 14 })
const course = Temporal.Duration.from('P2M3D')
const video = Temporal.Duration.from({ minutes: 90 })

The ISO duration string P2M3D means two months and three days.

A duration isn’t automatically a fixed number of milliseconds, because a month can have 28, 29, 30, or 31 days, and a day in a time zone can cross a clock change. Temporal sometimes needs a starting point to calculate a total:

const duration = Temporal.Duration.from({ months: 1 })

duration.total({
  unit: 'days',
  relativeTo: Temporal.PlainDate.from('2027-02-01'),
}) // 28

Change the starting month and the answer can change too.

Difference between dates

Use until() when moving from one value to another:

const start = Temporal.PlainDate.from('2026-08-10')
const end = Temporal.PlainDate.from('2026-09-17')

const difference = start.until(end, {
  largestUnit: 'months',
})

difference.toString() // 'P1M7D'

Use since() for the opposite direction:

end.since(start).days // 38

The options matter here: asking for months uses calendar arithmetic, while asking for days gives you a day count.

Round values deliberately

You can round Temporal values explicitly, choosing the smallest unit, increment, and rounding mode:

const time = Temporal.PlainTime.from('14:37:42')

time.round({
  smallestUnit: 'minute',
  roundingMode: 'halfExpand',
}).toString() // '14:38:00'

That’s safer than dividing milliseconds and hoping calendar behavior doesn’t matter.

Compare values

You don’t compare Temporal objects by reference with < or >. Use the static comparison method for the type:

const first = Temporal.PlainDate.from('2026-08-10')
const second = Temporal.PlainDate.from('2026-08-14')

Temporal.PlainDate.compare(first, second) // -1

The result is negative, zero, or positive.

Use .equals() when you need exact equality:

first.equals(second) // false

For ZonedDateTime, compare instants when ordering events, since two zoned values can represent the same instant while displaying different local fields.

PlainYearMonth and PlainMonthDay

Some values are incomplete by design.

Use PlainYearMonth for a billing period or expiry month:

const billingMonth = Temporal.PlainYearMonth.from('2026-08')

billingMonth.daysInMonth // 31

Use PlainMonthDay for a recurring annual date:

const birthday = Temporal.PlainMonthDay.from('08-10')

const thisYear = birthday.toPlainDate({ year: 2026 })

These types save you from fake placeholder values like “use 1970 for every birthday.”

Parsing strings

Temporal parses standardized, unambiguous strings:

Temporal.PlainDate.from('2026-08-10')
Temporal.PlainTime.from('14:30:00')
Temporal.PlainDateTime.from('2026-08-10T14:30:00')
Temporal.Instant.from('2026-08-10T12:30:00Z')
Temporal.ZonedDateTime.from(
  '2026-08-10T14:30:00+02:00[Europe/Rome]',
)

It doesn’t try to interpret human strings like next Friday, 08/10/26, or tomorrow morning, because those depend on locale, context, and assumptions. Parse user-facing formats with a dedicated parser, validate the fields, and then create the right Temporal type.

Serialize according to meaning

Every Temporal type has a stable string representation:

const date = Temporal.PlainDate.from('2026-08-10')
date.toString() // '2026-08-10'
date.toJSON() // '2026-08-10'

The right database representation depends on your domain.

Store an instant for events that happened

For audit logs and payments, store an RFC 3339 timestamp or integer epoch value:

2026-08-10T08:15:30.123Z

Store a plain date for date-only facts

For birthdays and publication dates, store:

2026-08-10

Don’t turn it into midnight UTC, because that invents a time and zone the value never had.

Store local fields and a zone for future schedules

For a recurring 09:00 Rome event, store the intended local time and Europe/Rome, since the future UTC offset can change with time-zone rules.

For a one-time event whose instant is already fixed, storing the instant plus display zone can be useful:

yesnoyesnoyesnoWhat does the valuemean?Already happened?Store InstantFuture localschedule?Store local fields +zoneDate only?Store PlainDatestringChoose the matchingTemporal type

Format for people

Machine strings work well for storage, while people need localized output. Temporal types provide toLocaleString() for that:

const date = Temporal.PlainDate.from('2026-08-10')

date.toLocaleString('it-IT', {
  dateStyle: 'long',
}) // '10 agosto 2026'

You can format a zoned value with date and time styles:

const workshop = Temporal.ZonedDateTime.from(
  '2026-08-14T09:00:00+02:00[Europe/Rome]',
)

workshop.toLocaleString('en-GB', {
  dateStyle: 'full',
  timeStyle: 'short',
})

Keep storage and presentation separate, and don’t parse a localized display string back into business data.

Convert between Date and Temporal

Libraries and browser APIs will keep returning Date values for a long time, so you’ll often convert at the edges of your code.

Convert a Date to an instant:

const legacy = new Date()

const instant = Temporal.Instant.fromEpochMilliseconds(
  legacy.getTime(),
)

Convert an instant back to Date:

const legacy = new Date(instant.epochMilliseconds)

Nanoseconds beyond millisecond precision are dropped in that conversion.

A plain date needs both a time zone and a clock time before it can become an instant:

const date = Temporal.PlainDate.from('2026-08-10')

const zoned = date.toZonedDateTime({
  timeZone: 'Europe/Rome',
  plainTime: Temporal.PlainTime.from('09:00'),
})

const legacy = new Date(zoned.epochMilliseconds)

Notice how the conversion makes you fill in those missing assumptions instead of guessing them silently.

Browser and runtime support

Temporal shipped in Firefox 139 in May 2025 and Chrome 144 in January 2026. Node.js 26 enables it by default, and Deno 2.7 exposes it as a stable API.

Safari stable still doesn’t ship the complete API, so public web apps still need a polyfill if you support Safari users.

I also cover Temporal alongside other native replacements in 10 browser APIs that replaced a library I used to install.

Feature-detect Temporal instead of checking browser versions:

if (globalThis.Temporal) {
  console.log('Native Temporal is available')
}

Use the polyfill correctly

Install the proposal champions’ polyfill:

npm install @js-temporal/polyfill

Then import the named export:

import { Temporal } from '@js-temporal/polyfill'

The package doesn’t touch the global object. Importing Temporal directly keeps the dependency explicit and works in both current and older runtimes.

If you want to use the native implementation when it’s available and load the polyfill only as a fallback:

const TemporalAPI = globalThis.Temporal ??
  (await import('@js-temporal/polyfill')).Temporal

const today = TemporalAPI.Now.plainDateISO()

Dynamic loading skips the polyfill download in browsers that support Temporal, though it makes app startup asynchronous. A regular bundled import is often simpler.

Check the polyfill’s bundle cost in your app before shipping it, since Temporal packs a lot of calendar and time-zone logic.

How I use Temporal in my projects

I already include Temporal examples in several tools on this site.

The date duration calculator compares legacy Date, date-fns, and Temporal. For adding seven calendar days, the Temporal version states the intent directly:

const base = Temporal.PlainDate.from('2026-08-10')
const result = base.add({ days: 7 })

The timestamp converter turns an epoch value into an instant and then into a UTC view:

const value = Temporal.Instant
  .fromEpochMilliseconds(1786349730123)
  .toZonedDateTimeISO('UTC')

The JavaScript date formatter generates toLocaleString() examples for Temporal alongside Intl.DateTimeFormat and date-fns.

Those tools are nice migration boundaries. The underlying calculator can keep accepting Date while the generated snippets show the safer model.

When modeling real app features with Temporal, match the type to the job:

  • Use Instant for webhook timestamps, audit events, token expiry, and uptime checks, where you care about an exact point on a timeline.
  • Use PlainDate for analytics day buckets and retention cutoff dates, since a reporting day is a calendar date rather than a midnight timestamp.
  • Use ZonedDateTime for countdown widgets and scheduled broadcasts when someone chooses a named time zone. That gets rid of manually juggling a datetime-local field, the browser offset, and an ISO string.

When moving an existing codebase over, migrate one boundary at a time. Swapping every Date call mechanically hides the modeling decisions Temporal is meant to surface.

Where Temporal is not the right tool

Temporal is built for date and time domain logic, not every kind of clock.

Measuring elapsed program time

Use performance.now() for request duration, animation timing, and benchmarks. It’s monotonic and unaffected by wall-clock adjustments:

const start = performance.now()
await runTask()
const elapsed = performance.now() - start

Tiny scripts with broad runtime support

If a script only generates an ISO timestamp and targets older environments, Date is still fine:

new Date().toISOString()

Adding a large polyfill for a single line usually isn’t worth it.

Libraries that require Date

Keep converting at the boundary until the library adds Temporal support. Don’t force-cast a Temporal object and hope it behaves like Date.

Natural-language parsing

Temporal doesn’t parse strings like “next Tuesday at lunch.” Use a dedicated parser first, then convert the validated result.

Testing Temporal code

Time-dependent tests break when business logic reads the real clock directly.

Pass the current value into the function instead:

function trialEndsAt(startedAt, days = 14) {
  return startedAt.add({ days })
}

const startedAt = Temporal.PlainDate.from('2026-08-10')

trialEndsAt(startedAt).toString() // '2026-08-24'

If a function needs “now,” give it a default so production callers stay clean while tests can override it:

function isExpired(expiresAt, now = Temporal.Now.instant()) {
  return Temporal.Instant.compare(now, expiresAt) >= 0
}

Make sure your tests cover the edge cases that ordinary examples miss:

  • leap day
  • end of month
  • start and end of year
  • daylight-saving gap
  • repeated daylight-saving time
  • negative duration
  • nanosecond rounding
  • invalid input with overflow: 'reject'
  • same instant displayed in different zones

Always use named zones in tests, and don’t rely on the machine running the suite being in your local time zone.

Common mistakes

Using PlainDateTime as a timestamp

A PlainDateTime has no time zone or offset, so pick a zone before treating it as an event.

Storing every value as UTC

UTC works for instants, not for birthdays, calendar-only deadlines, or future local schedules whose time-zone rules can change.

Using a fixed offset as a time zone

+02:00 can’t tell you what Rome’s offset will be in January.

Adding 24 hours when you mean tomorrow

Pass { days: 1 } on a zoned value to get the same local time tomorrow, and { hours: 24 } when you want 24 exact hours of elapsed time.

Comparing string output from different types

Use the type’s compare() or equals() methods instead, and be explicit about whether you’re comparing fields or instants.

Parsing localized strings

10/08/2026 means different dates in different locales. Accept structured fields or an explicit machine format instead.

Assuming the polyfill installs a global

Import { Temporal } and use that binding directly, or set up your own compatibility wrapper on purpose.

Calling Temporal.Now everywhere

Clock reads hidden inside business logic make tests flaky. Pass time in at the boundary.

A migration strategy

Don’t start with a global search and replace.

  1. Inventory what each date value means.
  2. Label it as instant, zoned schedule, plain date, plain time, or duration.
  3. Choose the matching Temporal type.
  4. Define the serialized database format.
  5. Convert at legacy library boundaries.
  6. Add tests for daylight-saving and month-end behavior.
  7. Decide whether native support or a polyfill fits each runtime.
  8. Migrate one workflow at a time.

Start with the parts where ambiguity already causes bugs: scheduling, reporting days, expiration logic, time-zone conversion, and calendar arithmetic.

A practical type chooser

Use this quick reference to pick the right Temporal type for a value:

yesnoyesnodate onlydate + timeyear + monthmonth + daytime onlyamountWhat are youstoring?Exact moment?Need named-zonedisplay orarithmetic?InstantZonedDateTimeDate fields?PlainDatePlainDateTimePlainYearMonthPlainMonthDayPlainTimeDuration

The mental model to keep

Temporal gives you separate types instead of trying to stretch one Date object across every case.

Use Instant for an exact point on the timeline, ZonedDateTime when that point follows a named time zone, the plain types when a value has no zone, and Duration for an amount of time (with a reference point whenever calendar units are involved). Beyond nicer methods, immutability, and safer daylight-saving arithmetic, choosing the right type tells anyone reading the code what kind of time value they’re working with before they read the logic around it.

Want me to talk about your product? You can sponsor this site.

Related posts about js: