Here's a bug that's very easy to ship.
You run a weekly online meetup. It starts at 6pm New York time every Tuesday. You store the first session as a timestamp, and to get the next ones you add seven days' worth of milliseconds. It works through February. Then, in the middle of March, the event page starts telling everyone the meetup is at 7pm.
Nothing in the code changed. The United States moved its clocks forward on March 14, 2027, and "seven days later" in milliseconds is no longer "next Tuesday at 6pm" on the wall clock. Your London attendees get a second surprise two weeks later, when the UK changes its clocks on a different date.
Date can't help you here, because a Date is only a number of milliseconds since 1970. It has no idea what time zone an event belongs to. Temporal is the replacement that does, and it's now built into Chrome, Edge and Firefox.
In this tutorial we'll build the date logic for that meetup app, piece by piece:
- Store an event so that it keeps its time zone.
- Show it in each viewer's local time.
- Repeat it weekly without drifting when clocks change.
- Show a countdown to the next session.
- Read a time from an
<input type="datetime-local">and catch times that don't exist. - Bill a subscription on the 31st without sliding to the 28th forever.
- Sort, compare and send it all to a server.
Every code sample was run, and the outputs in the comments are the real outputs.
Where Temporal works today
Before writing any code, here's the support situation. I took this from caniuse and MDN in late November 2026:
| Environment | Temporal support |
|---|---|
| Chrome and Edge | From version 144 |
| Firefox | From version 139 |
| Opera | From version 131 |
| Chrome for Android | Supported in current versions |
| Safari (macOS and iOS) | Not in a stable release. Available in Safari Technology Preview |
| Samsung Internet | Not supported |
| Node.js 24 | Behind the --harmony-temporal flag only |
MDN marks Temporal as "Limited availability", which means it isn't Baseline yet. Safari is the reason. In practice that means you need a polyfill for any public website, and that's fine: the polyfill uses the native version when it exists, so Chrome and Firefox users get native code and Safari users get the fallback.
Installing the polyfill
MDN links to two polyfills. The one by the proposal champions is @js-temporal/polyfill, and the one I use is temporal-polyfill by the FullCalendar team. It's about 19 kB, it's actively maintained (version 1.0.8 at the time of writing), and its global entry point leaves native Temporal alone:
npm install temporal-polyfill
// main.js: load this once, before any code that uses Temporal
import 'temporal-polyfill/global';
If you don't want polyfill code in your bundle for browsers that don't need it, load it only when it's missing:
if (!globalThis.Temporal) {
await import('temporal-polyfill/global');
}
One limitation: the default entry point only supports the ISO 8601 and Gregorian calendars. If you need Hebrew, Islamic, Japanese, Persian or other calendars, import from temporal-polyfill/full/global instead, which is larger.
For TypeScript users, TypeScript 6.0 added Temporal types to the esnext lib, so "lib": ["dom", "esnext"] is enough. On older versions, the polyfill's global entry ships its own type declarations.
The one idea you need: exact time vs wall-clock time
Almost every date bug comes from mixing up two different things:
- Exact time is a single moment for the whole planet. "The moment the meetup starts" is an exact time. A
Dateis an exact time. - Wall-clock time is what a clock on someone's wall says. "6pm" is a wall-clock time, and it means a different exact time in New York and in London.
An event in the real world is usually defined by wall-clock time in one specific place: "6pm in New York, every Tuesday." To get that right, you need to keep the place. Temporal makes you choose which kind of value you're holding, and that's most of its value. Here are the types and when I reach for each one:
| Type | What it holds | Use it for |
|---|---|---|
Temporal.Instant |
An exact moment, with no time zone | Log timestamps, "created at", values from a database timestamptz |
Temporal.ZonedDateTime |
An exact moment plus a time zone and calendar | Events, meetings, anything with a place |
Temporal.PlainDate |
A calendar date, no time, no zone | Birthdays, due dates, billing days |
Temporal.PlainTime |
A wall-clock time, no date, no zone | "Opens at 09:00" |
Temporal.PlainDateTime |
Date and wall-clock time, no zone | A value from <input type="datetime-local"> before you know the zone |
Temporal.PlainYearMonth |
Year and month | Credit card expiry, monthly reports |
Temporal.PlainMonthDay |
Month and day | Anniversaries |
Temporal.Duration |
A length of time like "3 days, 4 hours" | Countdowns, arithmetic |
Temporal.Now |
Functions that read the current time | Getting "now" in any of the types above |
Temporal itself is a namespace, like Math or Intl. You never write new Temporal().
A few habits from Date that you can drop right away:
- Months start at 1. February is
month: 2. - Every object is immutable. Methods like
add()return a new object and never change the original. - Invalid values don't roll over silently.
new Date(2027, 1, 30)gives you March 2.Temporal.PlainDate.from({ year: 2027, month: 2, day: 30 })gives you February 28 by default, and with{ overflow: 'reject' }it throws aRangeError.
Step 1: store the event with its time zone
The first session of our meetup is Tuesday, March 2, 2027, at 6pm in New York. In Temporal, that's a ZonedDateTime:
const firstSession = Temporal.ZonedDateTime.from('2027-03-02T18:00[America/New_York]');
firstSession.toString();
// '2027-03-02T18:00:00-05:00[America/New_York]'
The string format is worth a closer look, because it's how you'll store and send these values. It's an ISO 8601 date and time, then the UTC offset at that moment (-05:00, because New York is on standard time in early March), then the time zone name in square brackets. That bracket syntax is standardised as RFC 9557, so other languages and libraries can read it too.
The offset and the zone name together are what make this safe to store. The offset pins the exact moment. The zone name tells Temporal which rules to use when you do arithmetic later, and that's what fixes our DST bug.
ZonedDateTime won't guess the zone for you. If you give it a string with only an offset, it throws:
Temporal.ZonedDateTime.from('2027-03-09T18:00:00-05:00');
// RangeError (no time zone name in the string)
That might feel strict, but it's correct. -05:00 is New York in winter, but it's also Lima, Bogotá and Cancún all year round, and those places follow different rules. An offset alone isn't enough to know what "next week at the same time" means. If you really only have an offset, the value is an exact time, so parse it as an Instant:
Temporal.Instant.from('2027-03-09T18:00:00-05:00').toString();
// '2027-03-09T23:00:00Z'
JSON works the way you'd hope. JSON.stringify calls each object's toJSON(), which returns the same string as toString():
JSON.stringify({
startsAt: firstSession,
day: Temporal.PlainDate.from('2027-03-09'),
});
// '{"startsAt":"2027-03-02T18:00:00-05:00[America/New_York]","day":"2027-03-09"}'
Going the other way doesn't happen by magic: JSON.parse gives you strings back, and you call Temporal.ZonedDateTime.from() on them yourself. More on that in Step 7.
Step 2: show the time in each viewer's zone
Our attendees are spread out, and each of them wants to see the meetup in their own local time. withTimeZone() keeps the exact moment and changes only the zone you're looking from:
const viewerZone = Temporal.Now.timeZoneId(); // e.g. 'Europe/London'
const local = firstSession.withTimeZone(viewerZone);
local.toString();
// '2027-03-02T23:00:00+00:00[Europe/London]'
Temporal.Now.timeZoneId() reads the time zone from the browser, the same one Intl.DateTimeFormat().resolvedOptions().timeZone gives you.
For display, use toLocaleString(). It takes the same options as Intl.DateTimeFormat:
local.toLocaleString('en-GB', { dateStyle: 'full', timeStyle: 'short' });
// 'Tuesday, 2 March 2027 at 23:00'
An Instant has no zone of its own, so you pass one when formatting it:
firstSession.toInstant().toLocaleString('en-IN', {
timeZone: 'Asia/Kolkata',
dateStyle: 'medium',
timeStyle: 'short',
});
// '3 Mar 2027, 4:30 am'
That last one is a nice reminder of why this matters. For someone in Bengaluru, the Tuesday meetup is on a Wednesday morning. If you show only "Tuesday 6pm", you've told them the wrong day.
A small UX tip: show the event's own zone and the viewer's zone together when they're different, like "6:00 pm New York (11:00 pm your time)". People trust a time more when they can see where it came from.
Step 3: repeat it weekly without drifting
Now the bug from the introduction. Here's the naive version, using Instant, which behaves exactly like Date plus milliseconds:
const start = firstSession.toInstant();
for (let week = 0; week < 3; week++) {
const session = start.add({ hours: 168 * week });
console.log(session.toZonedDateTimeISO('America/New_York').toString());
}
// 2027-03-02T18:00:00-05:00[America/New_York]
// 2027-03-09T18:00:00-05:00[America/New_York]
// 2027-03-16T19:00:00-04:00[America/New_York] <- 7pm
There's the 7pm. On March 14 New York switched from UTC-5 to UTC-4, so 168 hours after 6pm is 7pm on the wall clock.
Instant won't even let you write add({ weeks: 1 }). It throws a RangeError, because a week isn't a fixed number of hours, and Instant has no time zone to work out how long a particular week is. That's a useful error: it pushes you towards the right type.
The right type is ZonedDateTime. When you add calendar units like days, weeks or months to it, Temporal keeps the wall-clock time and lets the exact time move. That's what people mean by "every Tuesday at 6pm":
for (let week = 0; week < 5; week++) {
const session = firstSession.add({ weeks: week });
const london = session.withTimeZone('Europe/London').toPlainTime();
const kolkata = session.withTimeZone('Asia/Kolkata').toPlainTime();
console.log(session.toString(), '| London', london.toString(), '| Kolkata', kolkata.toString());
}
Here's the real output, laid out as a table:
| Session (New York) | Offset | London | Kolkata |
|---|---|---|---|
| March 2, 18:00 | -05:00 | 23:00 | 04:30 |
| March 9, 18:00 | -05:00 | 23:00 | 04:30 |
| March 16, 18:00 | -04:00 | 22:00 | 03:30 |
| March 23, 18:00 | -04:00 | 22:00 | 03:30 |
| March 30, 18:00 | -04:00 | 23:00 | 03:30 |
New York stays at 6pm every week, which is what the organiser wants. Everyone else's local time moves, and that's correct too, because the clocks around them are changing on different dates. London sees the meetup an hour earlier for two weeks (the US changed on March 14, the UK on March 28), then it goes back to 11pm. India doesn't use daylight saving time, so Kolkata moves once and stays there.
This is a real thing to tell users about. If your app sends reminders, "Heads up: because of the clock change in the US, this week's meetup is at 22:00 your time" is the kind of message that saves people from missing it.
Finding the next session
On the event page you'll want the next upcoming session, not the first one ever. Keep adding weeks until you pass the current moment:
function nextSession(first, now = Temporal.Now.instant()) {
let session = first;
while (Temporal.Instant.compare(session.toInstant(), now) <= 0) {
session = session.add({ weeks: 1 });
}
return session;
}
const seriesStart = Temporal.ZonedDateTime.from('2026-09-01T18:00[America/New_York]');
nextSession(seriesStart, Temporal.Instant.from('2026-11-26T09:15:00Z')).toString();
// '2026-12-01T18:00:00-05:00[America/New_York]'
Two details here. The comparison uses Instant, because "has it started yet?" is a question about exact time. And now is a parameter with a default, which makes the function easy to test. We'll come back to that.
The loop is fine for a weekly series that's a few years old. If you have a series with thousands of past occurrences, work out how many weeks have passed with until() first and jump straight there.
Days that aren't 24 hours long
A ZonedDateTime can tell you about clock changes directly. hoursInDay gives the length of that local day, and getTimeZoneTransition() finds the next or previous change:
Temporal.ZonedDateTime.from('2027-03-14T12:00[America/New_York]').hoursInDay; // 23
Temporal.ZonedDateTime.from('2027-11-07T12:00[America/New_York]').hoursInDay; // 25
Temporal.ZonedDateTime.from('2027-01-01T00:00[America/New_York]')
.getTimeZoneTransition('next')
.toString();
// '2027-03-14T03:00:00-04:00[America/New_York]'
If you've ever built a calendar view where one day in March is mysteriously short, hoursInDay is the value you needed. And startOfDay() gives you the real start of a local day, which isn't always midnight. Chile, for example, moves its clocks forward at midnight, so on that day there is no 00:00:
Temporal.PlainDate.from('2026-09-06').toZonedDateTime('America/Santiago').toString();
// '2026-09-06T01:00:00-03:00[America/Santiago]'
Code that builds a day as "midnight plus 24 hours" breaks on days like this. Code that asks Temporal for the start of the day doesn't.
Step 4: a countdown to the next session
"Starts in 96 days, 13 hours" needs a Duration. You get one from until() (from this moment to that one) or since() (the reverse):
const now = Temporal.ZonedDateTime.from('2026-11-26T09:15[Europe/London]');
const session = Temporal.ZonedDateTime.from('2027-03-02T18:00[America/New_York]');
now.until(session).toString();
// 'PT2317H45M'
PT2317H45M is ISO 8601 duration notation for 2,317 hours and 45 minutes. By default, ZonedDateTime.until() uses hours as its largest unit, because hours always mean the same thing. To get days, ask for them with largestUnit:
now.until(session, { largestUnit: 'day' });
// RangeError
That's an error worth understanding. A "day" depends on a time zone: some days have 23 or 25 hours. Our two values are in different zones (London and New York), so Temporal refuses to guess whose days you mean. Convert one of them first:
const sessionInLondon = session.withTimeZone(now.timeZoneId);
now.until(sessionInLondon, { largestUnit: 'day' }).toString();
// 'P96DT13H45M'
now.until(sessionInLondon, { largestUnit: 'month', smallestUnit: 'minute' }).toString();
// 'P3M4DT13H45M'
I like that Temporal makes you decide. For a countdown, the viewer's own zone is usually the right answer, because "in 3 days" should mean three of their days.
Rounding and totals
Countdowns rarely need minutes. smallestUnit and roundingMode handle that:
const left = now.until(sessionInLondon, {
largestUnit: 'day',
smallestUnit: 'hour',
roundingMode: 'floor',
});
left.toString(); // 'P96DT13H'
left.days; // 96
left.hours; // 13
The default roundingMode for until() and since() is 'trunc', which cuts off the remainder. For a countdown, 'floor' and 'trunc' give the same result as long as the duration is positive. I write 'floor' anyway, so the intent is obvious to whoever reads it next.
If you want one number instead, use total():
now.until(session).total({ unit: 'hour' }); // 2317.75
Rounding a duration into months needs a starting date, because months have different lengths. Temporal throws a RangeError if you try it without one, so you pass relativeTo:
Temporal.Duration.from({ days: 45 })
.round({ largestUnit: 'month', relativeTo: Temporal.PlainDate.from('2027-01-31') })
.toString();
// 'P1M17D'
Formatting a duration for people
Don't build "3 days, 4 hours" by hand. Intl.DurationFormat does it in any language, and it has been Baseline since March 2025 (Chrome 129, Firefox 136, Safari 16.4), so it works even in browsers that need the Temporal polyfill:
const d = Temporal.Duration.from({ days: 3, hours: 4, minutes: 5 });
new Intl.DurationFormat('en', { style: 'long' }).format(d); // '3 days, 4 hours, 5 minutes'
new Intl.DurationFormat('en', { style: 'narrow' }).format(d); // '3d 4h 5m'
d.toLocaleString('en', { style: 'short' }); // '3 days, 4 hr, 5 min'
Step 5: read user input safely
Now the organiser side of the app: a form to schedule a new session. The HTML is simple:
<label for="starts">Starts</label>
<input id="starts" type="datetime-local" required />
<label for="zone">Time zone</label>
<select id="zone"></select>
<p id="warning" role="alert" hidden></p>
You can fill the <select> with every zone the browser knows about. Intl.supportedValuesOf('timeZone') returns several hundred names, so a searchable list is kinder than a plain dropdown, but the data source is the same:
const select = document.querySelector('#zone');
for (const id of Intl.supportedValuesOf('timeZone')) {
select.add(new Option(id, id, false, id === Temporal.Now.timeZoneId()));
}
The value of a datetime-local input is a string like '2027-03-14T02:30'. It has no zone, so it's a PlainDateTime, and that's exactly how you should parse it. Then you combine it with the zone the organiser picked:
const local = Temporal.PlainDateTime.from(input.value);
const startsAt = local.toZonedDateTime(select.value);
That works for almost every input. But look at the value I used: 2:30am on March 14, 2027, in New York. That time never happens. At 2:00am the clocks jump to 3:00am. What should the app do?
Temporal's answer is the disambiguation option, and you get to choose:
disambiguation |
Result for 02:30 on March 14 (doesn't exist) | Result for 01:30 on November 7 (happens twice) |
|---|---|---|
'compatible' (default) |
03:30, UTC-4 | 01:30, UTC-4 (the first one) |
'earlier' |
01:30, UTC-5 | 01:30, UTC-4 (the first one) |
'later' |
03:30, UTC-4 | 01:30, UTC-5 (the second one) |
'reject' |
throws a RangeError |
throws a RangeError |
The second column is the other DST problem. When clocks go back in November, 1:30am happens twice, an hour apart. 'compatible' picks the first one, which matches what Date and most older libraries do.
For a scheduling form, I don't want to throw and I don't want to change the organiser's input silently. So I accept the default and then check whether the result differs from what was typed:
function parseScheduleInput(value, timeZone) {
const local = Temporal.PlainDateTime.from(value);
const zoned = local.toZonedDateTime(timeZone, { disambiguation: 'compatible' });
const shifted = !zoned.toPlainDateTime().equals(local);
return { zoned, shifted };
}
parseScheduleInput('2027-03-14T02:30', 'America/New_York');
// zoned: 2027-03-14T03:30:00-04:00[America/New_York], shifted: true
parseScheduleInput('2027-03-14T09:00', 'America/New_York');
// zoned: 2027-03-14T09:00:00-04:00[America/New_York], shifted: false
When shifted is true, show a message: "2:30 am doesn't exist on March 14 in New York because the clocks go forward. We've scheduled it for 3:30 am." The organiser can fix it if that's wrong.
The repeated hour is less dangerous, because both versions are real times, but you can still detect it and ask. If 'earlier' and 'later' give two different moments that both show the time the user typed, that time is ambiguous:
function isAmbiguous(local, timeZone) {
const first = local.toZonedDateTime(timeZone, { disambiguation: 'earlier' });
const second = local.toZonedDateTime(timeZone, { disambiguation: 'later' });
return (
!first.equals(second) &&
first.toPlainDateTime().equals(local) &&
second.toPlainDateTime().equals(local)
);
}
isAmbiguous(Temporal.PlainDateTime.from('2027-11-07T01:30'), 'America/New_York'); // true
isAmbiguous(Temporal.PlainDateTime.from('2027-03-14T02:30'), 'America/New_York'); // false
The second check matters. For a time inside the spring gap, 'earlier' and 'later' also differ, but neither of them shows the time the user typed, so it's a gap, not a repeat.
Honestly, most meetups aren't scheduled at 2:30am. But reminders, cron-style jobs and anything shift-based hit these hours all the time. If you schedule recurring jobs on servers, the Cron Expression Explainer is a quick way to check when a pattern will fire, and it's a good place to remember that cron schedules have the same DST problem.
Date-only input
<input type="date"> gives you '2027-03-14'. That's a PlainDate:
const day = Temporal.PlainDate.from(dateInput.value);
This is also where Date causes one of its most famous bugs. new Date('2027-03-14') is parsed as midnight UTC, while new Date('2027-03-14T00:00') is parsed as midnight local time. So for anyone west of Greenwich, new Date('2027-03-14').getDate() returns 13. PlainDate doesn't have a time or a zone, so it can't be off by a day.
If you need the start of that day somewhere, or a specific time on it, convert explicitly:
day.toZonedDateTime('America/New_York').toString();
// '2027-03-14T00:00:00-05:00[America/New_York]'
day.toZonedDateTime({ timeZone: 'America/New_York', plainTime: '18:00' }).toString();
// '2027-03-14T18:00:00-04:00[America/New_York]'
Look at the offsets. Midnight on March 14 is still standard time (UTC-5), but 6pm the same day is daylight time (UTC-4). One day, two offsets.
Step 6: billing on the 31st
The meetup has a paid membership, and a member signed up on January 31. They should be charged on the last day of each month that doesn't have a 31st, and on the 31st when it exists.
Here's the version that seems obvious, adding one month to the previous billing date:
let billingDate = Temporal.PlainDate.from('2027-01-31');
const dates = [billingDate];
for (let i = 0; i < 4; i++) {
billingDate = billingDate.add({ months: 1 });
dates.push(billingDate);
}
// 2027-01-31, 2027-02-28, 2027-03-28, 2027-04-28, 2027-05-28
January 31 plus one month is February 28, because February 31 doesn't exist and the default overflow: 'constrain' clamps it to the last valid day. That part is right. The bug is in the next step: February 28 plus one month is March 28, and from there the member is billed on the 28th forever. Each step was correct on its own, and the total is wrong.
The fix is to always count from the anchor date:
const signup = Temporal.PlainDate.from('2027-01-31');
const schedule = Array.from({ length: 5 }, (_, i) => signup.add({ months: i }));
// 2027-01-31, 2027-02-28, 2027-03-31, 2027-04-30, 2027-05-31
This is a good rule for any repeating date: store the first occurrence and the count, and compute each one from the start. Don't chain. It applies to the weekly meetup too, and it's why Step 3 used firstSession.add({ weeks: week }).
When you want clamping to be an error instead, pass overflow: 'reject':
signup.add({ months: 1 }, { overflow: 'reject' });
// RangeError (there is no February 31)
A few other PlainDate properties that come up in billing code:
const d = Temporal.PlainDate.from('2027-03-09');
d.dayOfWeek; // 2 (Monday is 1, Sunday is 7)
d.daysInMonth; // 31
d.with({ day: 1 }).toString(); // '2027-03-01', the first of the month
Temporal.PlainDate.from('2028-02-01').inLeapYear; // true
with() returns a copy with some fields replaced. It clamps the same way add() does, so Temporal.PlainDate.from('2027-02-10').with({ day: 31 }) gives you February 28.
For anniversaries, PlainMonthDay handles February 29 sensibly:
Temporal.PlainMonthDay.from('02-29').toPlainDate({ year: 2027 }).toString();
// '2027-02-28'
Step 7: compare, sort and talk to the rest of your stack
Comparing values
The first time you try this, it throws:
sessionA < sessionB;
// TypeError
Temporal objects deliberately don't support < and >, because the answer would depend on which kind of time you meant. You use compare() (which returns -1, 0 or 1) or equals():
const sessions = [
'2027-03-09T18:00[America/New_York]',
'2027-03-09T21:00[Europe/London]',
'2027-03-10T04:00[Asia/Kolkata]',
].map((s) => Temporal.ZonedDateTime.from(s));
sessions.sort(Temporal.ZonedDateTime.compare);
// London 21:00 (21:00 UTC), Kolkata 04:00 (22:30 UTC), New York 18:00 (23:00 UTC)
compare uses exact time, so these sort by when they actually happen, whatever zone they're written in. Since it returns -1, 0 or 1, you can pass it straight to Array.prototype.sort.
equals() is stricter, and this one surprised me:
const ny = Temporal.ZonedDateTime.from('2027-03-09T18:00[America/New_York]');
const london = Temporal.ZonedDateTime.from('2027-03-09T23:00[Europe/London]');
ny.toInstant().equals(london.toInstant()); // true, same moment
ny.equals(london); // false, different time zones
Two ZonedDateTime values are only equal if the moment, the zone and the calendar all match. If you want "is this the same moment?", compare the instants.
Converting to and from Date
You'll still have Date objects coming from older code and libraries. Converting is lossless, apart from Temporal's extra precision (it works in nanoseconds, while Date works in milliseconds):
// Date to Temporal
const instant = legacyDate.toTemporalInstant();
// or, if you only have milliseconds:
const instant2 = Temporal.Instant.fromEpochMilliseconds(legacyDate.getTime());
// Temporal to Date
const backToDate = new Date(instant.epochMilliseconds);
Date.prototype.toTemporalInstant() exists in browsers with native Temporal, and the temporal-polyfill/global entry adds it too. If you use the side-effect-free import instead, fromEpochMilliseconds works everywhere.
Storing it in a database
There isn't one right schema, but here's what I'd do for the meetup:
- For "when did this happen" values (created at, paid at), store the exact time. In PostgreSQL that's a
timestamptzcolumn. Read it back as anInstant. - For "when should this happen" values (the session start), store the exact time and the IANA zone name in a separate text column, or store the full
ZonedDateTimestring. You need the zone name to do Step 3 correctly, andtimestamptzdoesn't keep it. - For dates without times (billing day, birthday), use a
datecolumn and read it as aPlainDate.
The zone name earns its column even if you never display it. Time zone rules change by law, sometimes with only a few months' notice. If a country drops daylight saving time next year, a stored zone name lets you recompute future sessions with the new rules. A stored offset can't do that.
Reading it back from JSON
Since JSON.parse gives you strings, revive the fields you know about:
const raw = await fetch('/api/sessions/next').then((r) => r.json());
const session = {
...raw,
startsAt: Temporal.ZonedDateTime.from(raw.startsAt),
};
I prefer doing this per field over a clever generic reviver that guesses from the string shape. A string that looks like a date isn't always meant to be one.
Testing date logic without flaky tests
Code that calls Temporal.Now directly is hard to test, because the answer changes every time you run it. The simplest fix is the one from Step 3: pass "now" in as a parameter with a default.
export function countdown(session, now = Temporal.Now.zonedDateTimeISO()) {
return now.until(session.withTimeZone(now.timeZoneId), {
largestUnit: 'day',
smallestUnit: 'minute',
});
}
import { expect, test } from 'vitest';
import { countdown } from './countdown.js';
test("counts calendar days across a US clock change", () => {
const session = Temporal.ZonedDateTime.from('2027-03-16T18:00[America/New_York]');
const now = Temporal.ZonedDateTime.from('2027-03-13T18:00[America/New_York]');
// Saturday 6pm to Tuesday 6pm is three days on the calendar...
expect(countdown(session, now).toString()).toBe('P3D');
// ...but only 71 hours pass, because March 14 is 23 hours long.
expect(now.until(session).toString()).toBe('PT71H');
});
I got this test wrong the first time I wrote it. I expected P2DT23H, because one of those days is short. Temporal says P3D, because largestUnit: 'day' on a ZonedDateTime counts days on the calendar, not 24-hour blocks. Once I thought about it, that's what a person means by "in 3 days". But it's exactly the kind of assumption a test should check, so write the test.
Write at least one test that crosses a DST change in each direction for every piece of date logic you care about. Those are the bugs that only show up twice a year, usually on a Sunday, when nobody's watching.
If your test runner is Node, remember that Node 24 only has Temporal behind a flag, so import the polyfill in your test setup file.
Checklist before you ship
- Pick the type on purpose. If the value has a place, it's a
ZonedDateTime. If it's a moment, it's anInstant. If it's a date on a calendar, it's aPlainDate. - Store the IANA zone name with any future event. An offset alone isn't enough.
- Add days, weeks and months to
ZonedDateTimeorPlainDate, never toInstant. - Compute repeating dates from the first occurrence. Don't chain
add()calls. - Convert to a common zone before using
until()orsince()with day, week, month or year units. - Check user input for gaps and repeats around clock changes, and tell the user when you adjust it.
- Use
compare()andequals(), never<,>or===. - Format with
toLocaleString()andIntl.DurationFormat, not string concatenation. - Load the polyfill until Safari ships Temporal, and use the
fullentry only if you need non-Gregorian calendars. - Inject "now" so your tests don't depend on the clock, and test across DST changes.
Wrapping up
For about thirty years, the JavaScript advice for dates has been "use a library", and that advice was right, because Date was too thin to build anything on. Temporal is the first time the language itself has the right concepts: exact time and wall-clock time, time zones that carry their rules, and calendar arithmetic that's honest about months.
It doesn't make time zones simple. They aren't simple. What it does is make the hard decisions visible. When Temporal throws a RangeError, it's usually asking you a question you should have been asking anyway: whose days? which 1:30am? what should happen on February 31?
The one thing that still slows adoption is Safari. Once it ships Temporal in a stable release, the polyfill can go and this becomes plain JavaScript. Until then, the polyfill's global entry point gives you the same API everywhere, and native speed where it's available.
If you're building the front end of a scheduling app like this one, our guide to optimistic UI with useOptimistic shows how to make the "book a session" button feel instant, and the HTML forms guide covers the input types used in Step 5 in more depth.