Sub topic 10
Displaying an Instant in Any Time Zone
This chapter assumes you already know that a Date holds one instant as epoch milliseconds, the difference between local and UTC getters, and how to build an Intl.DateTimeFormat with dateStyle, timeStyle, and component options. Here you will add the timeZone option. It lets you show one instant as the wall-clock time anywhere on Earth, no matter where the code runs.
The Core Idea: The Zone Belongs to the Formatter
A Date has no time zone. It has a single number. Methods like getHours() read that number through the runtime's default zone, and the getUTC* methods read it through UTC. Those are the only two views Date offers.
Intl.DateTimeFormat removes that limit. Its timeZone option takes any IANA time zone name, and the formatter converts the instant to that zone's wall-clock time when it formats. The stored value never changes.
const instant = new Date("2024-07-04T16:30:00Z");
for (const timeZone of ["UTC", "Asia/Tokyo", "America/Los_Angeles"]) {
const text = instant.toLocaleString("en-GB", { timeZone, timeZoneName: "short" });
console.log(timeZone, text);
}
// e.g.
// UTC 04/07/2024, 16:30:00 UTC
// Asia/Tokyo 05/07/2024, 01:30:00 GMT+9
// America/Los_Angeles 04/07/2024, 09:30:00 GMT-7The Tokyo line falls on a different calendar day. Converting the time zone can change the date, the weekday, and even the year, so always format the date part with the same zone you use for the time.
IANA Time Zone Names
The IANA time zone database (also called tzdata or the Olson database) names zones in Area/Location form, such as Europe/Berlin, America/Sao_Paulo, or Australia/Lord_Howe. Each name records that region's full history of offsets and daylight saving rules. When you format an instant from 1995, the engine uses the rules that applied in 1995.
Avoid using abbreviations and raw offsets as zone identifiers:
| Input | Why it is a problem |
|---|---|
| `"EST"`, `"CST"` | Ambiguous (`CST` means both China Standard Time and US Central Standard Time), and most abbreviations are rejected |
| `"+05:30"` | Accepted by newer engines, but a fixed offset has no daylight saving rules |
| `"Etc/GMT+5"` | Valid, but the sign is inverted: it means UTC−5 |
| `"America/New_York"` | Correct: carries every historical and future rule the database knows |
Zone names match without regard to case, so "america/new_york" works. resolvedOptions().timeZone returns the name with standard casing. Some old names, such as Asia/Calcutta and Asia/Kolkata, refer to the same zone, and the name an engine reports for them varies between versions. Don't compare zone strings with === to decide whether two zones are the same.
Invalid zones throw
An unknown zone throws a RangeError when you construct the formatter. It does not fall back quietly. That helps you catch typos, but user-supplied zones need a guard:
function safeFormatter(locale, timeZone, options = {}) {
try {
return new Intl.DateTimeFormat(locale, { ...options, timeZone });
} catch (err) {
if (err instanceof RangeError) {
return new Intl.DateTimeFormat(locale, { ...options, timeZone: "UTC" });
}
throw err;
}
}
const fmt = safeFormatter("en-US", "Mars/Olympus_Mons", { timeStyle: "short" });
console.log(fmt.resolvedOptions().timeZone); // "UTC"Listing supported zones
Intl.supportedValuesOf("timeZone") returns the engine's canonical zone names, which is useful for building a zone picker. Check that it exists first, because older runtimes lack it.
if (typeof Intl.supportedValuesOf === "function") {
const zones = Intl.supportedValuesOf("timeZone");
console.log(zones.length > 300, zones.includes("Europe/Paris")); // true true
}Showing the Zone: the timeZoneName Option
When you show times from more than one zone, label them. The timeZoneName option adds the label. Results for an instant in July with en-US:
| `timeZoneName` | Example output (America/New_York) |
|---|---|
| `"short"` | `EDT` |
| `"long"` | `Eastern Daylight Time` |
| `"shortOffset"` | `GMT-4` |
| `"longOffset"` | `GMT-04:00` |
| `"shortGeneric"` | `ET` |
| `"longGeneric"` | `Eastern Time` |
Short abbreviations exist only where the locale has a common one. For other zones you get an offset such as GMT+9. The generic forms leave out "Daylight" and "Standard", which suits recurring events like "every Monday, 9:00 AM Eastern Time".
Reading a Zone's Offset at an Instant
A zone's offset is not a constant. New York is UTC−5 in January and UTC−4 in July. To learn the offset at a specific instant, format with timeZoneName: "longOffset" and read that part:
function getOffsetMinutes(date, timeZone) {
const parts = new Intl.DateTimeFormat("en-US", {
timeZone,
timeZoneName: "longOffset",
}).formatToParts(date);
const name = parts.find((p) => p.type === "timeZoneName").value; // "GMT-04:00" or "GMT"
const match = name.match(/GMT([+-])(\d{2}):(\d{2})/);
if (!match) return 0; // plain "GMT" means offset zero
const sign = match[1] === "+" ? 1 : -1;
return sign * (Number(match[2]) * 60 + Number(match[3]));
}
console.log(getOffsetMinutes(new Date("2024-01-15T12:00:00Z"), "America/New_York")); // -300
console.log(getOffsetMinutes(new Date("2024-07-15T12:00:00Z"), "America/New_York")); // -240
console.log(getOffsetMinutes(new Date("2024-07-15T12:00:00Z"), "Asia/Kolkata")); // 330Use "en-US" here on purpose. Some locales format the offset with a Unicode minus sign (U+2212) or localized digits, and those would break the regular expression.
The Reverse Problem: Wall-Clock Time in a Zone to an Instant
Formatting goes from an instant to a zone's wall-clock time. The reverse is often needed too, for example "the meeting is at 09:00 in New York on 10 March 2024". Date offers no constructor for this. new Date(2024, 2, 10, 9) uses the runtime's zone, not New York's. You can calculate the instant with the offset helper above:
function zonedTimeToUtc(year, month, day, hour, minute, timeZone) {
const guess = Date.UTC(year, month, day, hour, minute); // treat wall time as if it were UTC
const offset1 = getOffsetMinutes(new Date(guess), timeZone);
let result = guess - offset1 * 60000;
const offset2 = getOffsetMinutes(new Date(result), timeZone);
if (offset2 !== offset1) result = guess - offset2 * 60000; // offset changed near a DST switch
return new Date(result);
}
const meeting = zonedTimeToUtc(2024, 2, 10, 9, 0, "America/New_York");
console.log(meeting.toISOString()); // "2024-03-10T13:00:00.000Z" (09:00 EDT, the day DST began)The second check matters because the offset at the first guess can differ from the offset at the real instant. Wall times inside a daylight saving gap (02:30 on that same morning does not exist) or overlap (01:30 on the autumn change happens twice) have no single correct answer. This helper picks one without telling you. If your app schedules events in user-chosen zones, decide how to handle gaps and overlaps explicitly. Temporal, covered in the last chapter, has built-in options for both.
The Default Zone Depends on Where Code Runs
If you omit timeZone, the formatter uses the runtime's default zone, which new Intl.DateTimeFormat().resolvedOptions().timeZone reports. In a browser, this is usually the user's system zone. On a server, it is the host's zone. Node.js reads it from the TZ environment variable, and containers and cloud functions are often set to UTC. Code that "looks right" on your laptop can therefore render server-side times hours off.
Common Errors
- Building a
Datefrom a string formatted in another zone, then formatting it again. The time gets shifted twice. Convert once and keep the instant. - Taking the date from
getDate()and the time from a formatter in a different zone, which gives mismatched days near midnight. - Hardcoding offsets like
-5for "New York", which is wrong for about eight months of the year. - Assuming offsets are whole hours. India is +05:30, Nepal +05:45, and
Australia/Lord_Howeshifts by only 30 minutes for daylight saving.
Exercise
A server in a UTC container runs new Date("2024-12-31T23:30:00Z").toLocaleDateString("en-US") for a user in Tokyo and shows "12/31/2024". What is wrong, and what call fixes it?
Show answer
With no timeZone option, the call uses the container's default zone (UTC), so it shows the UTC calendar date. In Tokyo (UTC+9) that instant is 08:30 on January 1, 2025. Pass the user's zone: toLocaleDateString("en-US", { timeZone: "Asia/Tokyo" }), which gives "1/1/2025".
Exercise
Using getOffsetMinutes, what values do you expect for Asia/Kathmandu and for UTC at any instant in 2024, and why does the helper need its if (!match) return 0 branch?
Show answer
Kathmandu returns 345 (UTC+05:45), and UTC returns 0. For a zero offset, longOffset formats as plain "GMT" with no sign or digits, so the regular expression finds no match. The branch maps that case to 0 instead of crashing on a null match.