Sub topic 12
Custom Layouts with formatToParts and Date Spans with formatRange
This chapter assumes you already know how to create an Intl.DateTimeFormat with a locale, component options, and the timeZone option. It covers two methods on the same formatter. formatToParts gives you the pieces of a formatted date. formatRange formats two dates as one span.
Why not just split the formatted string?
The output of format is meant for people to read. Its order, separators, and spacing change from one locale to another, and they can also change between engine versions. If you split it on " " or ",", the code breaks as soon as either one changes. formatToParts returns the same localized content as an array of typed objects, so you never have to parse text.
Working with parts
Each part has a type, such as "day", "month", "year", "weekday", "hour", "minute", "dayPeriod", "timeZoneName", or "literal". Literal parts hold the separators. If you join every value in order, you get exactly what format would return.
const d = new Date(Date.UTC(2024, 6, 4, 16, 30));
const fmt = new Intl.DateTimeFormat("en-US", {
weekday: "long",
month: "long",
day: "numeric",
hour: "numeric",
minute: "2-digit",
timeZone: "UTC",
});
const parts = fmt.formatToParts(d);
console.log(parts.map((p) => p.value).join("") === fmt.format(d)); // true
// Restyle: uppercase the weekday and keep the locale's order and separators.
const styled = parts
.map((p) => (p.type === "weekday" ? p.value.toUpperCase() : p.value))
.join("");
console.log(styled); // e.g. "THURSDAY, July 4 at 4:30 PM"
// Pick parts by type to build a fixed layout, such as a calendar badge.
const byType = Object.fromEntries(
parts.filter((p) => p.type !== "literal").map((p) => [p.type, p.value])
);
console.log(`${byType.day} ${byType.month.slice(0, 3).toUpperCase()}`); // "4 JUL"Keep the "restyle" approach when you can, because it preserves the locale's word order. Picking parts and putting them in your own order loses that order. That is fine for a fixed design such as a badge, but it is wrong for running text in other languages.
Formatting a span with formatRange
To show a date span such as a hotel stay, you could call format twice and put a dash between the results. That repeats shared fields, as in "Jul 4, 2024 – Jul 9, 2024". formatRange(start, end) lets the locale merge the fields the two dates share.
const range = new Intl.DateTimeFormat("en-US", { dateStyle: "medium", timeZone: "UTC" });
const start = new Date(Date.UTC(2024, 6, 4));
console.log(range.formatRange(start, new Date(Date.UTC(2024, 6, 9)))); // e.g. "Jul 4 – 9, 2024"
console.log(range.formatRange(start, new Date(Date.UTC(2024, 7, 2)))); // e.g. "Jul 4 – Aug 2, 2024"
console.log(range.formatRange(start, new Date(Date.UTC(2025, 0, 3)))); // e.g. "Jul 4, 2024 – Jan 3, 2025"Engines often put thin or narrow no-break spaces around the dash. Do not compare these strings against hard-coded text in tests. If end is earlier than start, current engines format the range anyway, but older ones throw a RangeError. Validate the order yourself.
formatRangeToParts combines both ideas. Each part has an extra source field with the value "startRange", "endRange", or "shared", so you can style the start and end dates differently.
| Method | Returns | Use it for |
|---|---|---|
| `format` | string | Plain display |
| `formatToParts` | array of `{type, value}` | Restyling or custom layouts |
| `formatRange` | string | Compact date spans |
| `formatRangeToParts` | array of `{type, value, source}` | Styling span endpoints separately |
Exercise
You need markup where only the month name of a date is wrapped in <strong>, in whatever position the user's locale puts it. Which method do you use, and how?
Show answer
Use formatToParts on a formatter that includes a month option. Map over the parts, wrap the value in <strong> when p.type === "month", leave the other parts unchanged, and join the results. The locale's order and separators stay as they are.
Exercise
Why does formatRange(start, end) produce "Jul 4 – 9, 2024" instead of repeating the month and year?
Show answer
formatRange compares the two dates and uses the locale's range patterns to write each shared field (here the month and year) once. Only the fields that differ are shown on both sides.