Lesson 15 of 50JavaScript in depth
Dates, Time Zones and Intl
Understand what a Date really is, store instants and show them in the user's zone, survive DST, format with Intl, and know when to use Temporal.
A user in Sydney books a delivery for "Tuesday" and the confirmation email says Monday. A daily sales report counts one hour twice every November. A Next.js page shows "10:00" for a split second, then flicks to "21:00" with a hydration warning in the console. Every one of these is a real ticket, and they all come from the same few misunderstandings about how JavaScript represents time. Date bugs are expensive because they hide: they pass every test written in the developer's own time zone and only show up for users elsewhere, or twice a year. This lesson gives you the mental model that prevents them, the Intl APIs that format dates, numbers and lists for any locale, and Temporal, the modern replacement for Date.
What a Date really is
A Date holds exactly one thing: a number of milliseconds since 1 January 1970 at midnight UTC (the Unix epoch). It has no time zone and no format. Everything else is a view computed from that number. The getHours(), getDate() and toString() family show it in the runtime's local time zone, which is the user's zone in a browser and usually UTC on a server. The getUTCHours() family and toISOString() show it in UTC.
Press Run (⌘ Enter) to see what happens.Run it and the last two lines depend on your machine. Change your computer's time zone and run again: the timestamp and ISO string stay the same, the local hour moves. That is the whole model. One instant, many local views.
Date also has two famous design flaws. Months are 0-based (0 is January, 11 is December) while days are 1-based. And dates are mutable: setDate, setMonth and friends change the object in place, so passing a Date into a function that "adds a week" can quietly change the caller's value. Setters also overflow instead of failing, which is handy for "add one day" and surprising for months.
What does this print?
const d = new Date(2026, 0, 31); // 31 January, local time d.setMonth(1); // "make it February" console.log(d.getMonth(), d.getDate());
Parsing: the trap in new Date(string)
Parsing strings is where most bugs start, because the rules are inconsistent:
new Date("2026-03-01"), a date-only ISO string, is parsed as midnight UTC.new Date("2026-03-01T00:00"), date and time without an offset, is parsed as midnight local time.new Date("2026-03-01T00:00Z")or"...+01:00"has an explicit offset, so it means the same instant everywhere.- Anything else, such as
"03/01/2026"or"1 March 2026", is implementation-defined. Browsers mostly agree today, but the spec does not promise it, and03/01means 1 March in the US and 3 January in the UK.
Press Run (⌘ Enter) to see what happens.That last line is the classic "date picker shows the day before" bug. A form gives you "2026-03-01", you call new Date() on it, and every user west of London sees 28 February. If a value is a calendar date (a birthday, a due date, a holiday), do not turn it into an instant at all. Keep it as the string "2026-03-01", or as a Temporal.PlainDate.
new Date(input.value).getDate(). What do they get?Store instants, display in zones
The rule that prevents most bugs: store and transmit instants in UTC, convert to a time zone only at the edge where a human reads it. In practice that means ISO 8601 strings ending in Z in JSON (which is what JSON.stringify produces for a Date, as Json and storage showed), timestamptz or equivalent columns in the database, and formatting with an explicit timeZone when you display.
The user typed a wall-clock time in their zone. On its own, 09:00 is ambiguous: it is not yet a moment in time.
Press Run (⌘ Enter) to see what happens.There is one important exception. Future wall-clock events ("the shop opens at 09:00 every day", "remind me at 8 am on my birthday") should be stored as the local date and time plus the zone id, then turned into an instant when needed. Governments change DST rules, sometimes with only weeks of notice. If you precomputed the UTC instant for next year's 09:00 opening, a rule change makes it wrong. The IANA time zone database, which browsers and Node ship, is updated several times a year for exactly this reason. That is also why you never hand-roll time zone math with fixed offsets.
DST: a day is not 24 hours
In zones with daylight saving time, one day a year has 23 hours and another has 25. On 8 March 2026, clocks in New York jump from 02:00 to 03:00. So "add 24 hours" and "add one day" are different operations.
Sat 12:00 EST
Start: 17:00 UTC
A daily job is scheduled for noon local time. Offset is UTC minus 5.
Sun 01:59 EST
Last minute of winter time
Wall clock and UTC still differ by 5 hours.
Sun 02:00
Clocks jump to 03:00 EDT
The hour from 02:00 to 02:59 does not exist today. Offset becomes UTC minus 4.
Sun 13:00 EDT
Saturday + 24 hours
Adding 86,400,000 ms lands at 13:00 local, an hour late. The job drifts.
Sun 12:00 EDT
Saturday + 1 calendar day
Adding a day in the zone keeps the wall clock at noon. Only 23 real hours passed.
What does this print?
const start = new Date("2026-03-07T17:00:00Z"); // noon in New York
const plus24h = new Date(start.getTime() + 24 * 60 * 60 * 1000);
const hour = new Intl.DateTimeFormat("en-US", {
timeZone: "America/New_York", hour: "numeric", hourCycle: "h23",
});
console.log(hour.format(start), hour.format(plus24h));With plain Date you can only do calendar math in the runtime's zone: d.setDate(d.getDate() + 1) keeps the local wall clock, but only for the machine's zone, which on a server is usually UTC. For another zone you need Temporal or a library. The two other DST traps: local times that do not exist (02:30 on the spring-forward night) and times that happen twice (01:30 on the fall-back night). Libraries and Temporal let you choose how to resolve those. Hand-written code usually picks one by accident.
Intl: formatting for humans
Intl is the built-in internationalisation API, backed by the same Unicode CLDR locale data as most operating systems. It covers far more than dates, and it ships in every browser and in Node, so you rarely need a formatting library.
Press Run (⌘ Enter) to see what happens.What each one is for at work:
- DateTimeFormat: every displayed date. Use
dateStyle/timeStylefor standard formats, or fields like{ weekday: "short", hour: "2-digit" }.formatToPartsgives you pieces to style separately. Always passtimeZoneon servers. - RelativeTimeFormat: "3 hours ago", "yesterday". You pick the unit yourself, usually by comparing the difference against thresholds.
- NumberFormat: currency (it knows the euro goes after the number in German and that yen has no decimals), percentages, units, and compact notation like
1.3Mfor dashboards. Never format money withtoFixedand a hardcoded symbol. - PluralRules: picks the plural category. English has two cardinal forms, Arabic has six, so
count === 1 ? "item" : "items"is wrong outside English. i18n libraries use this underneath. - ListFormat: "Ada, Sam, and Lin", with the right conjunction and comma rules per language.
- Collator: locale-aware sorting. Default
sort()compares UTF-16 code units, soZebracomes beforeappleanditem10beforeitem2. A collator withnumeric: truefixes both. - Segmenter: splits text into graphemes (what users see as characters), words or sentences. The Strings and templates lesson mentioned it for emoji. It is the correct way to truncate a username or count characters for a limit.
Creating a formatter is relatively expensive, because it loads and resolves locale data. Calling format on an existing one is cheap. In a list of 1,000 rows, create the formatter once outside the loop (or in a module-level constant), not inside a render function on every row.
Match each UI requirement to the Intl API.
Temporal: the replacement for Date
Temporal is the new date and time API built into JavaScript, designed to fix everything above. It ships in Firefox (since 2025) and in Chromium-based browsers (since early 2026). Check Can I Use for Safari and for your Node version before relying on it without a polyfill (temporal-polyfill or @js-temporal/polyfill). TypeScript 6.0 includes its types when your lib includes esnext.
The big idea is separate types for separate meanings, all immutable, with 1-based months:
| Type | Means | Example |
|---|---|---|
Temporal.Instant | An exact moment, no zone | A log timestamp |
Temporal.ZonedDateTime | A moment in a specific IANA zone | A meeting in Europe/London |
Temporal.PlainDate | A calendar date, no time or zone | A birthday, a due date |
Temporal.PlainTime | A wall-clock time | "Opens at 09:00" |
Temporal.PlainDateTime | Date and time, no zone | A form value before you know the zone |
Temporal.Duration | An amount of time | 1 day, 2 hours |
// Parse an exact instant and view it in New York
const start = Temporal.Instant.from("2026-03-07T17:00:00Z")
.toZonedDateTimeISO("America/New_York");
start.add({ hours: 24 }).hour; // 13: exactly 24 real hours later
start.add({ days: 1 }).hour; // 12: same wall clock, DST-aware
// Calendar dates never touch time zones
const due = Temporal.PlainDate.from("2026-01-31");
due.add({ months: 1 }).toString(); // "2026-02-28": clamped, not overflowed
// Comparisons and differences are explicit
Temporal.PlainDate.compare(due, Temporal.PlainDate.from("2026-02-01")); // -1
due.until("2026-03-01", { largestUnit: "day" }).days; // 29
// Converting to and from legacy code
const legacy = new Date();
Temporal.Instant.fromEpochMilliseconds(legacy.getTime());Every bug in this lesson becomes either impossible or explicit. You cannot add months to an Instant (it has no calendar), you cannot confuse a birthday with a timestamp, and DST behaviour is a documented option, not an accident.
Temporal, a library, or Date?
- New code where Temporal is available (or you accept a polyfill): use Temporal for anything involving zones, calendar math or durations.
- Existing codebases: date-fns (with
@date-fns/tzfor zones) or Day.js with its timezone plugin are common and fine. Luxon has a model close to Temporal. Moment.js is in maintenance mode; do not start new work with it. - Plain Date is fine for timestamps you only store, compare and format with
Intl. - Never do zone math by adding or subtracting hours by hand.
Server and client: hydration mismatches
In server-rendered React (Next.js and others), the HTML is rendered on a server, usually in UTC, then hydrated in the browser, in the user's zone. If a component formats a date without an explicit zone, the two renders produce different text, React warns about a hydration mismatch, and the user sees the time flick from one value to another.
// Bug: the server formats in UTC, the browser in the user's zone
export function PostedAt({ iso }: { iso: string }) {
return <time dateTime={iso}>{new Date(iso).toLocaleString()}</time>;
}
// Fix 1: format with a known zone (the user's saved preference, or a fixed one)
export function PostedAtZoned({ iso, timeZone }: { iso: string; timeZone: string }) {
const text = new Intl.DateTimeFormat("en-GB", {
dateStyle: "medium", timeStyle: "short", timeZone,
}).format(new Date(iso));
return <time dateTime={iso}>{text}</time>;
}The other fixes: render a zone-neutral value on the server (a date only, or "2 hours ago" computed on a stable boundary) and format the local version in a client component after it mounts, or, for a single timestamp element where a brief difference is acceptable, add suppressHydrationWarning to that element only. Relative times like "3 minutes ago" also mismatch because time passes between the two renders, so they need the same care. In every case, put the ISO string in <time dateTime> so the machine-readable value is always correct.
- Unix epoch
- Midnight UTC on 1 January 1970. A
Datestores milliseconds since then. - UTC
- Coordinated Universal Time, the zone-free reference that instants are stored in.
- IANA time zone
- A named zone such as
Europe/London, with its full history of offsets and DST rules. - ISO 8601
- The standard date format, such as
2026-03-29T08:00:00Z. Sorts correctly as text. - DST
- Daylight saving time. Shifts a zone's offset, so some days have 23 or 25 hours.
- Intl
- The built-in API for locale-aware formatting of dates, numbers, plurals, lists and sorting.
- Temporal
- The modern, immutable date and time API with separate types for instants, zoned times and plain dates.