JavaScript Intl DateTimeFormat formatToParts() Method

JavaScript Intl DateTimeFormat formatToParts() Method is used to allow locale-aware formatting of string produced by DayTimeFormat formatters. This method is particularly useful when you want more control over the formatting of a date string, such as when you’re building a custom date picker or calendar.

Syntax

Intl.DateTimeFormat.formatToParts(date)

Parameters

date(optional): The date object you want to format.

Return Value

The method returns an array of objects containing the formatted date in parts.

Example 1: How to Use JavaScript Intl DateTimeFormat formatToParts() Method

let date = new Date('2023-09-02');
let dateTimeFormat = new Intl.DateTimeFormat('en-US',
 { year: 'numeric', month: 'long', day: 'numeric' }).formatToParts(date);

console.log(dateTimeFormat);

Output

{ type: 'month', value: 'September' },
{ type: 'literal', value: ' ' },
{ type: 'day', value: '2' },
{ type: 'literal', value: ', ' },
{ type: 'year', value: '2023' }

Example 2: Using Time Components

let date = new Date(Date.UTC(2023, 8, 2, 2, 0, 0));

const dateTimeFormat = new Intl.DateTimeFormat('en-US', {
 year: 'numeric',
 month: 'short',
 day: 'numeric',
 hour: '2-digit',
 minute: '2-digit',
 second: '2-digit'
}).formatToParts(date);

console.log(dateTimeFormat);

Output

{ type: 'month', value: 'Sep' },
{ type: 'literal', value: ' ' },
{ type: 'day', value: '2' },
{ type: 'literal', value: ', ' },
{ type: 'year', value: '2023' },
{ type: 'literal', value: ', ' },
{ type: 'hour', value: '07' },
{ type: 'literal', value: ':' },
{ type: 'minute', value: '30' },
{ type: 'literal', value: ':' },
{ type: 'second', value: '00' },
{ type: 'literal', value: ' ' },
{ type: 'dayPeriod', value: 'AM' }

Browser Compatibility

Chrome 24+ Edge 12+ Firefox 29+ Safari 10+ Opera 15+
Yes Yes Yes Yes Yes

That’s it!

Related posts

JavaScript Int.DateTimeFormat() constructor

JavaScript Intl.DateTimeFormat.format() Method

JavaScript Intl DateTimeFormat formatRange() Method

JavaScript Intl DateTimeFormat formatRangeToParts() Method

JavaScript Intl DateTimeFormat supportedLocalesOf() Method

Leave a Comment