Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Intl.DateTimeFormat: format a date into parts with formatToParts()

Get the parts of a localized date or time so you can highlight a field such as the month without splitting the text on separators or assuming a field order.

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, not a static constructor method. Call it as formatter.formatToParts(date). Unlike format(), it is not automatically bound to the instance: calling the extracted function without the right this throws a TypeError.

Pass a Date or a timestamp in milliseconds since the Unix epoch, not seconds. Omitting the argument or passing undefined uses the current time from Date.now(). An invalid Date or an out-of-range timestamp throws a RangeError. This method formats values; it does not parse date text. Runtimes with Temporal integration can also accept some Temporal.Plain* types; passing a Temporal.ZonedDateTime directly throws a TypeError.

The result is an array of { type, value } objects in display order; both properties are strings. A type such as month, day, or year identifies a field, while literal marks pattern text such as a comma, space, or word. With named-year calendars, relatedYear (the corresponding Gregorian year) can replace year, and the pattern can also include yearName (the year's name).

Select parts by type, not by array index. To reproduce format() for the same formatter and date, join every value with no separator, including the literal values. Locale and options such as calendar and time zone affect the result; exact spelling and punctuation can vary between runtimes even for the same locale. Do not use the result as a data interchange format.

Examples

const formatter = new Intl.DateTimeFormat("en-US", {
  timeZone: "UTC",
  year: "numeric",
  month: "long",
  day: "numeric",
});
const date = new Date("2024-07-09T12: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 date, locale, and UTC time zone. The first `true` confirms there is a `month` part; the second confirms that the joined values match `format()`.

Related lessons

  • JavaScript · Lesson 15 · Basic · Version: 4

Sources