Course contentsShow
← JavaScript
Lesson 2215 of 2,72346. InternationalizationFree lesson

FormatToParts for Granular Access

Call formatToParts to receive an array of parts (day, month, literal) for custom rendering logic.

FormatToParts for Granular Access

You'll learn how to break down formatted date-time strings into individual parts for precise control over custom rendering.

The Core Idea

When you call format() on a DateTimeFormat instance, you get a complete string like "12/25/2023". But what if you want to style the month differently, wrap the year in a <span>, or rearrange the parts? The formatToParts() method solves this by returning an array of objects, each representing a distinct piece of the formatted output—day, month, year, literal separators, and more.

Think of it like disassembling a watch: instead of one working timepiece, you get the gears, hands, and case separately. You can now reassemble them however you like.

How It Works

const formatter = new Intl.DateTimeFormat('en-US', {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit'
});

const date = new Date('2023-12-25');
const parts = formatter.formatToParts(date);

console.log(parts);
// [
//   { type: 'month', value: '12' },
//   { type: 'literal', value: '/' },
//   { type: 'day', value: '25' },
//   { type: 'literal', value: '/' },
//   { type: 'year', value: '2023' }
// ]

Each object has a type (identifying the part) and a value (the formatted text). This lets you build custom markup:

const html = parts.map(part => {
  if (part.type === 'month') return `<strong>${part.value}</strong>`;
  if (part.type === 'year') return `<em>${part.value}</em>`;
  return part.value;
}).join('');

console.log(html); // "<strong>12</strong>/<em>25</em>/2023"

Use Cases

This is invaluable when you need to apply CSS classes, insert icons between parts, or completely rearrange the output while respecting locale formatting rules.

Key Takeaway: formatToParts() gives you an array of labeled date-time fragments, enabling fine-grained custom rendering logic that plain format() can't provide.