Skip to content

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.

15 min read0/4 questions

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.

JavaScript
const d = new Date(Date.UTC(2026, 2, 29, 8, 0)); // 29 March 2026, 08:00 UTCconsole.log(d.getTime()); // the only thing actually storedconsole.log(d.toISOString()); // the same instant in UTC, ISO 8601console.log(d.getUTCHours(), "UTC hours");console.log(d.getHours(), "local hours, wherever this code runs");console.log(Intl.DateTimeFormat().resolvedOptions().timeZone);
Output
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.

Predict the outputJavaScript

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());
Need a nudge? Hints walk you through it.

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, and 03/01 means 1 March in the US and 3 January in the UK.
JavaScript
console.log(new Date("2026-03-01").toISOString());console.log(new Date("2026-03-01T00:00").toISOString());console.log(new Date("2026-03-01T00:00Z").toISOString());// In New York, the first one is still 28 February on the local calendar:const fmt = new Intl.DateTimeFormat("en-US", { timeZone: "America/New_York", dateStyle: "medium" });console.log(fmt.format(new Date("2026-03-01")));
Output
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.

Quick check
A user in Los Angeles picks 1 March 2026 in a date input. Your code runs new Date(input.value).getDate(). What do they get?
Need a nudge? A hint rules out a wrong answer.

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.

One instant, from form to three screens
Form input: 29 Mar 09:00, Europe/LondonForm input29 Mar 09:00, Europe/LondonInstant: 2026-03-29T08:00:00ZInstant2026-03-29T08:00:00ZDatabase: UTC timestamp + zone idDatabaseUTC timestamp + zone idNew York: Sun 04:00New YorkSun 04:00London: Sun 09:00LondonSun 09:00Tokyo: Sun 17:00TokyoSun 17:00resolve zonestore UTCformatformatformat

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.

1/4
JavaScript
const meeting = new Date("2026-03-29T08:00:00Z");for (const timeZone of ["Europe/London", "America/New_York", "Asia/Tokyo"]) { const f = new Intl.DateTimeFormat("en-GB", { timeZone, dateStyle: "full", timeStyle: "short" }); console.log(timeZone.padEnd(18), f.format(meeting));}
Output
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.

The night New York springs forward (8 March 2026)
  1. Sat 12:00 EST

    Start: 17:00 UTC

    A daily job is scheduled for noon local time. Offset is UTC minus 5.

  2. Sun 01:59 EST

    Last minute of winter time

    Wall clock and UTC still differ by 5 hours.

  3. 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.

  4. Sun 13:00 EDT

    Saturday + 24 hours

    Adding 86,400,000 ms lands at 13:00 local, an hour late. The job drifts.

  5. 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.

Predict the outputJavaScript

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));
Need a nudge? Hints walk you through it.

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.

JavaScript
const when = new Date("2026-10-22T14:05:00Z");const opts = { dateStyle: "medium", timeStyle: "short", timeZone: "UTC" };console.log(new Intl.DateTimeFormat("en-US", opts).format(when));console.log(new Intl.DateTimeFormat("de-DE", opts).format(when)); const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });console.log(rtf.format(-1, "day"), "|", rtf.format(3, "hour")); const eur = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });const compact = new Intl.NumberFormat("en", { notation: "compact" });console.log(eur.format(1234.5), "|", compact.format(1_250_000)); const ordinal = new Intl.PluralRules("en-US", { type: "ordinal" });const suffix = { one: "st", two: "nd", few: "rd", other: "th" };console.log([1, 2, 3, 4, 11, 22].map((n) => n + suffix[ordinal.select(n)]).join(" ")); console.log(new Intl.ListFormat("en", { type: "conjunction" }).format(["Ada", "Sam", "Lin"])); const files = ["item10", "item2", "Zebra", "apple"];console.log(files.toSorted(), files.toSorted(new Intl.Collator("en", { numeric: true }).compare)); const seg = new Intl.Segmenter("en", { granularity: "grapheme" });const pair = "\u{1F44D}\u{1F3FD}\u{1F1EC}\u{1F1E7}"; // thumbs up with skin tone, UK flagconsole.log(pair.length, [...seg.segment(pair)].length);
Output
Press Run (⌘ Enter) to see what happens.

What each one is for at work:

  • DateTimeFormat: every displayed date. Use dateStyle/timeStyle for standard formats, or fields like { weekday: "short", hour: "2-digit" }. formatToParts gives you pieces to style separately. Always pass timeZone on 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.3M for dashboards. Never format money with toFixed and 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, so Zebra comes before apple and item10 before item2. A collator with numeric: true fixes 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 the pairs0/5 matched

Match each UI requirement to the Intl API.

Choose an item, then its match on the other side.

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:

TypeMeansExample
Temporal.InstantAn exact moment, no zoneA log timestamp
Temporal.ZonedDateTimeA moment in a specific IANA zoneA meeting in Europe/London
Temporal.PlainDateA calendar date, no time or zoneA birthday, a due date
Temporal.PlainTimeA wall-clock time"Opens at 09:00"
Temporal.PlainDateTimeDate and time, no zoneA form value before you know the zone
Temporal.DurationAn amount of time1 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/tz for 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.

components/PostedAt.tsx
// 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.

Key terms
Unix epoch
Midnight UTC on 1 January 1970. A Date stores 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.