Course contentsShow
← Web Development
Lesson 2764 of 2,98249. Dates, Times, and Numbers on the WebFree lesson

formatToParts for Custom Rendering

Use formatToParts to get an array of date components for building custom date displays with styling.

What You'll Learn

You'll learn how to use formatToParts() to break down a formatted date into individual components, giving you fine-grained control over styling and layout of each piece.

The Problem with Plain Strings

When you call format() on an Intl.DateTimeFormat instance, you get back a complete formatted string like "January 15, 2024". That's great for basic display, but what if you want to style the month differently than the day? Or wrap each component in its own HTML element? You'd have to parse the string yourself—messy and error-prone.

Breaking Dates Into Parts

The formatToParts() method solves this by returning an array of objects, where each object represents one component of the formatted date with both its type and value:

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

const date = new Date('2024-01-15');
const parts = formatter.formatToParts(date);

console.log(parts);
// [
//   { type: 'month', value: 'January' },
//   { type: 'literal', value: ' ' },
//   { type: 'day', value: '15' },
//   { type: 'literal', value: ', ' },
//   { type: 'year', value: '2024' }
// ]

Custom Rendering Example

Now you can map over these parts to create custom HTML:

const html = parts.map(part => {
  if (part.type === 'month') {
    return `<span class="month">${part.value}</span>`;
  }
  if (part.type === 'day') {
    return `<span class="day">${part.value}</span>`;
  }
  return part.value; // literals and other parts
}).join('');

// Result: <span class="month">January</span> <span class="day">15</span>, 2024

You maintain full control over styling, accessibility attributes, or any custom rendering logic while still benefiting from locale-aware formatting.

Key Takeaway: formatToParts() decomposes formatted dates into type-labeled components, enabling custom styling and rendering while preserving internationalization support.