Sub topic 12
Custom Layouts with formatToParts and Date Spans with formatRange
This chapter assumes you already know how to build an Intl.DateTimeFormat with dateStyle, timeStyle, component options, and the timeZone option, which the earlier chapters covered. It adds two tools to that formatter. formatToParts returns the localized output as typed pieces you can rearrange or restyle. formatRange formats two instants as a single span, such as "Jan 10 – 20, 2024".
Why Not Just Parse the Output of format()
People often call format() and then cut the string apart with split or a regular expression to get the month or the hour. That code breaks in three ways:
- Order changes by locale.
en-USputs the month first,en-GBputs the day first, andja-JPstarts with the year. - Separators change between engine versions. Newer ICU data puts a narrow no-break space (U+202F) before "PM" where older data used a plain space. A regex that matches
" PM"stops matching after a runtime upgrade. - Digits can change. Locales such as
ar-EGuse Arabic-Indic digits by default, so\dmatches nothing.
formatToParts avoids all three problems. It returns the same output the formatter would produce, already split into labeled pieces.
How formatToParts Works
formatToParts(date) returns an array of { type, value } objects. If you join every value in order, you get exactly the string format(date) would return.
const fmt = new Intl.DateTimeFormat("en-US", {
weekday: "short",
month: "short",
day: "numeric",
hour: "numeric",
minute: "2-digit",
timeZone: "UTC",
});
const d = new Date(Date.UTC(2024, 6, 4, 16, 5)); // 2024-07-04T16:05:00Z
const parts = fmt.formatToParts(d);
console.log(parts);
// Roughly:
// [ { type: "weekday", value: "Thu" }, { type: "literal", value: ", " },
// { type: "month", value: "Jul" }, { type: "literal", value: " " },
// { type: "day", value: "4" }, { type: "literal", value: ", " },
// { type: "hour", value: "4" }, { type: "literal", value: ":" },
// { type: "minute", value: "05" }, { type: "literal", value: " " },
// { type: "dayPeriod", value: "PM" } ]
console.log(parts.map((p) => p.value).join("") === fmt.format(d)); // trueThe literal pieces carry the separators and connecting words. The other types you will see are listed below.
| type | Example value | Notes |
|---|---|---|
| `weekday` | `Thu`, `Thursday` | Present only if requested or implied by `dateStyle` |
| `era` | `AD` | Shown with `era` option or some calendars |
| `year`, `month`, `day` | `2024`, `Jul`, `04` | Month may be a name or digits |
| `hour`, `minute`, `second` | `16`, `05`, `09` | Padding follows `"2-digit"` vs `"numeric"` |
| `fractionalSecond` | `123` | Needs `fractionalSecondDigits` |
| `dayPeriod` | `PM`, `in the afternoon` | Older Chrome versions used the lowercase `dayperiod` |
| `timeZoneName` | `GMT+9`, `PDT` | Needs `timeZoneName` |
| `relatedYear`, `yearName` | `2024`, `甲辰` | Appear with non-Gregorian calendars such as `chinese` |
| `literal` | `, `, ` at `, `/` | Everything that is not a date field |
Pattern 1: Restyle Without Changing the Layout
To change how one field looks while keeping the locale's order and separators, map over the parts and join them.
const fmt = new Intl.DateTimeFormat("de-DE", {
weekday: "long",
day: "numeric",
month: "long",
timeZone: "UTC",
});
const d = new Date(Date.UTC(2024, 6, 4));
const text = fmt
.formatToParts(d)
.map((p) => (p.type === "month" ? `[${p.value.toUpperCase()}]` : p.value))
.join("");
console.log(text); // "Donnerstag, 4. [JULI]"This approach works for any locale, so it is the right choice for UI work such as making the day number bold or coloring the weekday. You keep the translation and only change the presentation.
Pattern 2: Build Your Own Layout
Sometimes you need a fixed layout made from localized values. A common case is a "YYYY-MM-DD HH:mm" stamp in a time zone other than UTC. toISOString cannot produce this because it always uses UTC. Collect the non-literal parts into an object and put them into a template.
function partsMap(formatter, date) {
const map = {};
for (const { type, value } of formatter.formatToParts(date)) {
if (type !== "literal") map[type] = value;
}
return map;
}
const tokyo = new Intl.DateTimeFormat("en-US", {
timeZone: "Asia/Tokyo",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
hourCycle: "h23",
});
function toTokyoStamp(date) {
const p = partsMap(tokyo, date);
return `${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute}`;
}
console.log(toTokyoStamp(new Date("2024-07-04T16:05:00Z"))); // "2024-07-05 01:05"
console.log(toTokyoStamp(new Date("2024-07-04T15:00:00Z"))); // "2024-07-05 00:00"A few choices in this code prevent bugs:
hourCycle: "h23"instead ofhour12: false. Withhour12: false, some engines pick theh24cycle and print midnight as24.h23always gives00through23.- A Latin-digit locale (
en-US). The template needs ASCII digits. If you must use a user's locale, addnumberingSystem: "latn"to the options. - Skipping literals. Several literals appear in one output. Writing them all into a single key would keep only the last one, and you don't need them anyway.
Formatting Spans with formatRange
formatRange(start, end) formats two instants as one range. The point is that it removes repeated fields: if both dates fall in the same year, the locale's range pattern prints the year once.
const range = new Intl.DateTimeFormat("en-US", { dateStyle: "medium", timeZone: "UTC" });
const jan10 = new Date(Date.UTC(2024, 0, 10));
const jan20 = new Date(Date.UTC(2024, 0, 20));
const feb5 = new Date(Date.UTC(2024, 1, 5));
const jan3next = new Date(Date.UTC(2025, 0, 3));
console.log(range.formatRange(jan10, jan20)); // e.g. "Jan 10 – 20, 2024"
console.log(range.formatRange(jan10, feb5)); // e.g. "Jan 10 – Feb 5, 2024"
console.log(range.formatRange(jan10, jan3next)); // e.g. "Jan 10, 2024 – Jan 3, 2025"
console.log(range.formatRange(jan10, jan10)); // "Jan 10, 2024" (collapses to one date)The spaces around the en dash may be thin spaces (U+2009) depending on the ICU version. Don't compare this output to hard-coded strings in tests unless you pin the runtime.
Time ranges work the same way. The repeated day period is dropped:
const meeting = new Intl.DateTimeFormat("en-US", {
hour: "numeric",
minute: "2-digit",
timeZone: "America/New_York",
});
const start = new Date("2024-07-04T13:00:00Z");
const end = new Date("2024-07-04T15:30:00Z");
console.log(meeting.formatRange(start, end)); // e.g. "9:00 – 11:30 AM"What Decides the Collapse
The engine compares the fields as they appear in the formatter's time zone and calendar, not the raw time values. It finds the largest field that differs (year, month, day, day period, hour, minute) and picks the locale's range pattern for that field. Two consequences follow:
- A range that sits within one day in UTC can cross midnight in
Asia/Tokyo, so it prints both dates there. - Differences smaller than any displayed field are invisible. A
dateStyle: "medium"range from 09:00 to 17:00 on the same day collapses to a single date.
Tagging Range Output with formatRangeToParts
formatRangeToParts adds a source property to each part: "startRange", "endRange", or "shared".
const range = new Intl.DateTimeFormat("en-US", { dateStyle: "medium", timeZone: "UTC" });
const parts = range.formatRangeToParts(
new Date(Date.UTC(2024, 0, 10)),
new Date(Date.UTC(2024, 0, 20))
);
for (const p of parts) {
console.log(p.source.padEnd(10), p.type.padEnd(8), JSON.stringify(p.value));
}
// Roughly:
// shared month "Jan"
// shared literal " "
// startRange day "10"
// shared literal " – "
// endRange day "20"
// shared literal ", "
// shared year "2024"Because day appears twice, the partsMap helper from Pattern 2 would overwrite the start day with the end day. Group by source first, or keep the array as it is.
Common Errors and Edge Cases
| Situation | What happens |
|---|---|
| Either argument is an Invalid Date | `RangeError` |
| An argument is `undefined` | `TypeError` |
| `start` is later than `end` | Older engines threw `RangeError`; current spec formats it as given |
| Numbers passed instead of Dates | Accepted and treated as epoch milliseconds |
| Checking for `dayPeriod` in old Chrome | The type may be `dayperiod`; compare case-insensitively if you support old browsers |
| `Object.fromEntries` over all parts | Literal keys collide; filter literals first |
Exercises
Exercise
Write a function that returns the weekday name of a Date as seen in "America/Los_Angeles", in the user's locale, without parsing a formatted string. What does it return for new Date("2024-07-05T03:00:00Z") with locale "en-US"?
Show answer
const wd = new Intl.DateTimeFormat("en-US", { weekday: "long", timeZone: "America/Los_Angeles" }); const weekday = (d) => wd.formatToParts(d).find((p) => p.type === "weekday").value; It returns "Thursday", because 03:00 UTC on July 5 is 20:00 PDT on July 4.
Exercise
A formatter uses { dateStyle: "medium", timeZone: "UTC" }. You call formatRange for 2024-03-01T08:00Z and 2024-03-01T18:00Z and get a single date with no dash. Why, and how do you show the span?
Show answer
formatRange collapses fields that are equal in the output. Only year, month, and day are displayed, and they match, so the range collapses to one date. Add time fields, for example { dateStyle: "medium", timeStyle: "short", timeZone: "UTC" }, so the differing hours are visible and the output becomes something like "Mar 1, 2024, 8:00 AM – 6:00 PM".
Exercise
Your partsMap helper produces "2024-07-05 24:05" for a midnight-hour instant in some browsers. What option causes this and what fixes it?
Show answer
hour12: false can resolve to the h24 hour cycle, which writes midnight as 24. Replace it with hourCycle: "h23", which always uses 00–23.