Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Intl.DateTimeFormat.formatToParts(): date and time parts

Get the parts of a localized date or time so you can style one component without guessing the field order or splitting the formatted text on punctuation.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

formatter.formatToParts()
formatter.formatToParts(date)

Intl.DateTimeFormat.prototype.formatToParts is an instance method of Intl.DateTimeFormat. Instead of the single string returned by format(), it gives you an array of { type, value } objects in display order. Both properties are strings. Joining all the value strings with join("") reproduces format() for the same formatter and input. Unlike the function returned by format, formatToParts is not automatically bound. Pass date => formatter.formatToParts(date) as a callback or use bind; an incompatible this throws TypeError.

Select parts by type, such as month or dayPeriod, not by array index. Keep literal parts: they can contain spaces, punctuation, or words. In some calendars, relatedYear (the corresponding Gregorian year) appears instead of year, sometimes alongside yearName (the year's name). Preserve unfamiliar parts too. Locale, options, and runtime data can affect the output. Use the parts for display, not for parsing or storage. In a browser, insert values as text with textContent, not innerHTML.

In ECMA-402 for ECMAScript 2024, pass a Date or a number of milliseconds since the Unix epoch. The method coerces the argument to a number; it does not parse date strings. Omission or undefined uses the current time at the call. An invalid Date or an out-of-range timestamp throws RangeError.

Runtimes with Temporal integration also accept Temporal.Instant and the Temporal.Plain* types specified for this method, subject to type-specific calendar and formatting restrictions. Check support in your target runtime. Passing a Temporal.ZonedDateTime directly throws TypeError. To get parts for the same instant in its zone, pass the result of toInstant() and set the formatter's timeZone to that object's zone.

Examples

{
  const formatter = new Intl.DateTimeFormat("en-US", {
    timeZone: "UTC",
    calendar: "gregory",
    year: "numeric",
    month: "long",
    day: "numeric",
  });
  const date = new Date("2024-07-05T12:00:00Z");
  const parts = formatter.formatToParts(date);

  console.log(parts.some(({ type }) => type === "month"));
  console.log(parts.map(({ value }) => value).join("") === formatter.format(date));
}

Result

true
true

The example fixes the instant, locale, and UTC time zone. The first `true` confirms a `month` part exists. The second confirms the joined values match `format(date)` without assuming any particular separators.

Related lessons

  • JavaScript · Lesson 25 · Advanced · Version: 4

Sources