Intl.DateTimeFormat.prototype.formatToParts()

Наши волонтёры ещё не перевели данную статью на Русский. Присоединяйтесь к нам и помогите сделать эту работу!
Вы можете также прочитать эту статью на English (US).

The Intl.DateTimeFormat.prototype.formatToParts() method allows locale-aware formatting of strings produced by DateTimeFormat formatters.

Syntax

Intl.DateTimeFormat.prototype.formatToParts(date)

Parameters

date Optional
The date to format.

Return value

An Array of objects containing the formatted date in parts.

Description

The formatToParts() method is useful for custom formatting of date strings. It returns an Array of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts. The structure the formatToParts() method returns, looks like this:

[
  { type: 'day', value: '17' },
  { type: 'weekday', value: 'Monday' }
]

Possible types are the following:

day
The string used for the day, for example "17".
dayPeriod
The string used for the day period, for example, "AM" or "PM".
era
The string used for the era, for example "BC" or "AD".
hour
The string used for the hour, for example "3" or "03".
literal
The string used for separating date and time values, for example "/", ",", "o'clock", "de", etc.
minute
The string used for the minute, for example "00".
month
The string used for the month, for example "12".
second
The string used for the second, for example "07" or "42".
timeZoneName
The string used for the name of the time zone, for example "UTC".
weekday
The string used for the weekday, for example "M", "Monday", or "Montag".
year
The string used for the year, for example "2012" or "96".

Examples

DateTimeFormat outputs localized, opaque strings that cannot be manipulated directly:

var date = Date.UTC(2012, 11, 17, 3, 0, 42);

var formatter = new Intl.DateTimeFormat('en-us', {
  weekday: 'long',
  year: 'numeric',
  month: 'numeric',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  hour12: true,
  timeZone: 'UTC'
});

formatter.format(date);
// "Monday, 12/17/2012, 3:00:42 AM"

However, in many User Interfaces there is a desire to customize the formatting of this string. The formatToParts method enables locale-aware formatting of strings produced by DateTimeFormat formatters by providing you the string in parts:

formatter.formatToParts(date);

// return value: 
[ 
  { type: 'weekday',   value: 'Monday' }, 
  { type: 'literal',   value: ', '     }, 
  { type: 'month',     value: '12'     }, 
  { type: 'literal',   value: '/'      }, 
  { type: 'day',       value: '17'     }, 
  { type: 'literal',   value: '/'      }, 
  { type: 'year',      value: '2012'   }, 
  { type: 'literal',   value: ', '     }, 
  { type: 'hour',      value: '3'      }, 
  { type: 'literal',   value: ':'      }, 
  { type: 'minute',    value: '00'     }, 
  { type: 'literal',   value: ':'      }, 
  { type: 'second',    value: '42'     }, 
  { type: 'literal',   value: ' '      }, 
  { type: 'dayPeriod', value: 'AM'     } 
]

Now the information is available separately and it can be formatted and concatenated again in a customized way. For example by using Array.prototype.map(), arrow functions, a switch statement, template literals, and Array.prototype.reduce().

var dateString = formatter.formatToParts(date).map(({type, value}) => { 
  switch (type) {
    case 'dayPeriod': return `<b>${value}</b>`; 
    default : return value; 
  } 
}).reduce((string, part) => string + part);

This will make the day period bold, when using the formatToParts() method.

console.log(formatter.format(date));
// "Monday, 12/17/2012, 3:00:42 AM"

console.log(dateString);
// "Monday, 12/17/2012, 3:00:42 <b>AM</b>"

Polyfill

A polyfill for this feature is available in the proposal repository.

Specifications

Specification Status Comment
ECMAScript Internationalization API 4.0 (ECMA-402)
The definition of 'Intl.DateTimeFormat.prototype.formatToParts' in that specification.
Draft Initial definition

Browser compatibility

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
formatToPartsChrome Full support 57
Notes
Full support 57
Notes
Notes Before version 71, formatToParts() returned an object with an incorrectly cased type key of dayperiod. Version 71 and later use the specification defined dayPeriod. See Chromium bug 865351.
Edge Full support YesFirefox Full support 51IE No support NoOpera Full support YesSafari Full support 11WebView Android Full support 57
Notes
Full support 57
Notes
Notes Before version 71, formatToParts() returned an object with an incorrectly cased type key of dayperiod. Version 71 and later use the specification defined dayPeriod. See Chromium bug 865351.
Chrome Android Full support 57
Notes
Full support 57
Notes
Notes Before version 71, formatToParts() returned an object with an incorrectly cased type key of dayperiod. Version 71 and later use the specification defined dayPeriod. See Chromium bug 865351.
Edge Mobile No support NoFirefox Android Full support 56Opera Android No support NoSafari iOS Full support 11Samsung Internet Android Full support 7.0nodejs Full support Yes

Legend

Full support  
Full support
No support  
No support
See implementation notes.
See implementation notes.

See also

Метки документа и участники

Внесли вклад в эту страницу: mdnwebdocs-bot, fscholz, shvaikalesh, arai, nmve, SphinxKnight, rxaviers, Sebastianz, schlagi123
Обновлялась последний раз: mdnwebdocs-bot,