Sub topic 9
Formatting Dates with Intl.DateTimeFormat
This chapter assumes you know how a Date stores an instant as epoch milliseconds, and how local time and UTC give two views of that instant. It also assumes you have read the Intl basics: locale tags such as "en-US", the options object, and resolvedOptions(). Every example passes timeZone: "UTC" so the output is the same on every machine. The next chapter covers time zones properly.
Intl.DateTimeFormat turns a Date into text that suits a given locale. Instead of building strings from getMonth() and getDate(), you describe what to show, and the locale decides how to show it: which order, which separators, which month names.
The working model
A formatter is built once from two inputs, a locale and an options object. From then on it can format any number of dates.
const event = new Date(Date.UTC(2024, 6, 4, 16, 30)); // 2024-07-04T16:30:00Z
const fmt = new Intl.DateTimeFormat("en-US", { timeZone: "UTC" });
console.log(fmt.format(event)); // "7/4/2024"
console.log(fmt.format(event.getTime())); // "7/4/2024" (a number works too)
console.log(typeof fmt.format()); // "string" (no argument means "now")The constructor does most of the work. It negotiates the locale, checks the options, fills in defaults, and picks a pattern. Calling format only fills that pattern with values from the instant.
Style options: dateStyle and timeStyle
The quickest way to get good output is dateStyle and timeStyle. Each takes "full", "long", "medium", or "short". You can use one of them or both.
const event = new Date(Date.UTC(2024, 6, 4, 16, 30));
for (const style of ["full", "long", "medium", "short"]) {
const f = new Intl.DateTimeFormat("en-US", {
dateStyle: style,
timeStyle: style,
timeZone: "UTC",
});
console.log(style.padEnd(6), f.format(event));
}
// e.g.
// full Thursday, July 4, 2024 at 4:30:00 PM Coordinated Universal Time
// long July 4, 2024 at 4:30:00 PM UTC
// medium Jul 4, 2024, 4:30:00 PM
// short 7/4/24, 4:30 PMThe styles are locale-aware presets. Use them when "a normal-looking date for this user" is all you need. Your code stays short, and translators and locale data decide the details for you.
Component options: choosing individual fields
When a preset doesn't fit, ask for individual fields. Each option names a field and how to display it.
| Option | Values |
|---|---|
| `weekday` | `"long"`, `"short"`, `"narrow"` |
| `era` | `"long"`, `"short"`, `"narrow"` |
| `year` | `"numeric"`, `"2-digit"` |
| `month` | `"numeric"`, `"2-digit"`, `"long"`, `"short"`, `"narrow"` |
| `day`, `hour`, `minute`, `second` | `"numeric"`, `"2-digit"` |
| `fractionalSecondDigits` | `1`, `2`, `3` |
| `dayPeriod` | `"narrow"`, `"short"`, `"long"` (e.g. "in the afternoon") |
| `timeZoneName` | `"short"`, `"long"`, `"shortOffset"`, `"longOffset"`, and others |
The important point is that you choose the fields and the locale chooses the layout. The order of keys in your object has no effect on the output.
const event = new Date(Date.UTC(2024, 6, 4, 16, 30));
const opts = { year: "numeric", month: "long", day: "numeric", weekday: "short", timeZone: "UTC" };
for (const locale of ["en-US", "en-GB", "de-DE", "ja-JP"]) {
console.log(locale, new Intl.DateTimeFormat(locale, opts).format(event));
}
// e.g.
// en-US Thu, July 4, 2024
// en-GB Thu 4 July 2024
// de-DE Do., 4. Juli 2024
// ja-JP 2024年7月4日(木)Your options are a request, not a contract. The engine looks through the locale's available patterns and picks the best match. If a locale has no pattern with exactly the combination you asked for, you may get a slightly different width. To see what was actually chosen, call resolvedOptions().
Defaults
If you ask for no date or time fields at all, the formatter falls back to year, month, and day set to "numeric". That explains the "7/4/2024" in the first example. If you ask for any field, only the fields you named appear:
const event = new Date(Date.UTC(2024, 6, 4, 16, 30));
const hourOnly = new Intl.DateTimeFormat("en-US", { hour: "numeric", timeZone: "UTC" });
console.log(hourOnly.format(event)); // "4 PM" (no date at all)12-hour and 24-hour clocks
Each locale has a default hour cycle. You can override it with hour12 (a boolean) or hourCycle ("h11", "h12", "h23", "h24").
const event = new Date(Date.UTC(2024, 6, 4, 16, 30));
const base = { hour: "numeric", minute: "2-digit", timeZone: "UTC" };
console.log(new Intl.DateTimeFormat("en-US", base).format(event)); // "4:30 PM"
console.log(new Intl.DateTimeFormat("en-US", { ...base, hour12: false }).format(event)); // "16:30"
console.log(new Intl.DateTimeFormat("de-DE", base).format(event)); // "16:30"
console.log(new Intl.DateTimeFormat("de-DE", { ...base, hourCycle: "h12" }).format(event)); // e.g. "4:30 PM"When you set both, hour12 wins and hourCycle is ignored. "h24" is rare: it shows midnight as 24:00, so avoid it unless a specification requires it.
Calendars and numbering systems
Locales can also change the calendar and the digits used. You can set them with Unicode extension keys in the locale tag (-u-ca-, -u-nu-) or with the calendar and numberingSystem options.
const event = new Date(Date.UTC(2024, 6, 4));
const dateOpts = { dateStyle: "long", timeZone: "UTC" };
console.log(new Intl.DateTimeFormat("en-US-u-ca-buddhist", dateOpts).format(event)); // e.g. "July 4, 2567 BE"
console.log(new Intl.DateTimeFormat("ar-EG", dateOpts).format(event)); // Arabic-Indic digits
console.log(new Intl.DateTimeFormat("en-US", { ...dateOpts, numberingSystem: "arab" }).format(event));If your app needs Gregorian years whatever the locale, set calendar: "gregory" explicitly.
Common errors
Mixing styles with components
You cannot combine dateStyle or timeStyle with weekday, year, month, day, hour, minute, second, fractionalSecondDigits, era, dayPeriod, or timeZoneName. The constructor throws:
try {
new Intl.DateTimeFormat("en-US", { dateStyle: "medium", weekday: "long" });
} catch (e) {
console.log(e instanceof TypeError, e.message); // true, message varies by engine
}Options that change the pattern without adding a field are allowed alongside styles. These include hour12, hourCycle, timeZone, calendar, and numberingSystem. If you need a style plus one extra field, switch fully to component options.
Formatting an Invalid Date
format throws a RangeError for an Invalid Date. It does not return "Invalid Date" the way toString() does. Check the input before formatting:
const fmt = new Intl.DateTimeFormat("en-US", { dateStyle: "medium", timeZone: "UTC" });
function safeFormat(value) {
const d = new Date(value);
return Number.isNaN(d.getTime()) ? "—" : fmt.format(d);
}
console.log(safeFormat("2024-07-04")); // "Jul 4, 2024"
console.log(safeFormat("garbage")); // "—"Expecting a fixed pattern
Code that does fmt.format(d).split("/") works in en-US and fails in de-DE, which uses dots. Formatted output is for people to read. For data, use toISOString(). For individual fields, use formatToParts, covered in a later chapter.
Forgetting the time zone
Without timeZone, the formatter uses the runtime's zone. A date stored as UTC midnight can show up as the previous day for users west of UTC. Decide which zone you mean every time. The next chapter covers this in detail.
Passing format as a callback
format is a getter that returns a function already bound to its formatter. That means dates.map(fmt.format) works safely, and you don't need to wrap it in an arrow function.
const fmt = new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", timeZone: "UTC" });
const dates = [Date.UTC(2024, 0, 1), Date.UTC(2024, 11, 25)].map((t) => new Date(t));
console.log(dates.map(fmt.format)); // ["1 Jan", "25 Dec"]Exercise
You want output like "Thursday, July 4, 2024" in US English, with a 24-hour time "16:30" after it, for the instant 2024-07-04T16:30:00Z shown in UTC. A colleague writes { dateStyle: "full", hour: "2-digit", minute: "2-digit", hour12: false, timeZone: "UTC" }. What happens, and how do you fix it?
Show answer
The constructor throws a TypeError, because dateStyle cannot be combined with the hour and minute component options. Fix 1: use only component options, { weekday: "long", month: "long", day: "numeric", year: "numeric", hour: "2-digit", minute: "2-digit", hour12: false, timeZone: "UTC" }, which gives e.g. "Thursday, July 4, 2024 at 16:30". Fix 2: keep the styles and use { dateStyle: "full", timeStyle: "short", hour12: false, timeZone: "UTC" }. This works because hour12 is allowed alongside styles.
Exercise
new Intl.DateTimeFormat("en-US", { month: "long", timeZone: "UTC" }).format(new Date(Date.UTC(2024, 6, 4))) returns "July". Why doesn't it show the day and year, when a formatter with no options shows "7/4/2024"?
Show answer
The default of numeric year, month, and day applies only when you request no date or time fields at all. Once you name any field (here, month), the formatter shows only the fields you asked for.
Exercise
A report loops over 10,000 rows and calls new Date(row.ts) and then fmt.format(...). A few rows have a null or malformed timestamp, and the whole report crashes. What is the error, and what is the minimal fix?
Show answer
format throws a RangeError ("Invalid time value") for an Invalid Date. Check Number.isNaN(d.getTime()) before calling format, and show a placeholder for rows that fail. Note also that new Date(null) is the epoch, 1970-01-01, not an Invalid Date. Treat a null timestamp as missing explicitly before you construct the Date.