Intl.DateTimeFormat.prototype.formatToParts()

Intl.DateTimeFormat 实例的 formatToParts() 方法允许对此 Intl.DateTimeFormat 对象生成的字符串进行区域设置感知格式设置。

¥The formatToParts() method of Intl.DateTimeFormat instances allows locale-aware formatting of strings produced by this Intl.DateTimeFormat object.

Try it

语法

¥Syntax

js
formatToParts(date)

参数

¥Parameters

date Optional

要格式化的日期。

返回值

¥Return value

包含部分格式化日期的 Array 个对象。

¥An Array of objects containing the formatted date in parts.

描述

¥Description

formatToParts() 方法对于日期字符串的自定义格式很有用。它返回 Array 个对象,其中包含特定于区域设置的标记,可以从中构建自定义字符串,同时保留特定于区域设置的部分。formatToParts() 方法返回的结构如下所示:

¥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:

js
[
  { type: "day", value: "17" },
  { type: "weekday", value: "Monday" },
];

可能的类型如下:

¥Possible types are the following:

day

用于当天的字符串,例如 "17"

dayPeriod

用于日期间的字符串,例如 "AM""PM""in the morning""noon"

era

用于时代的字符串,例如 "BC""AD"

fractionalSecond

用于秒小数部分的字符串,例如 "0""00""000"

hour

用于表示小时的字符串,例如 "3""03"

literal

用于分隔日期和时间值的字符串,例如 "/"",""o'clock""de" 等。

minute

用于分钟的字符串,例如 "00"

month

用于月份的字符串,例如 "12"

relatedYear

用于相关 4 位公历年份的字符串,如果日历的表示形式是年份名称而不是年份,例如 "2019"

second

用于第二个的字符串,例如 "07""42"

timeZoneName

用于时区名称的字符串,例如 "UTC"。默认是当前环境的时区。

weekday

用于工作日的字符串,例如 "M""Monday""Montag"

year

用于年份的字符串,例如 "2012""96"

yearName

相关上下文中用于年份名称的字符串,例如 "geng-zi"

示例

¥Examples

DateTimeFormat 输出无法直接操作的本地化、不透明字符串:

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

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

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

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

然而,在许多用户界面中都希望自定义该字符串的格式。formatToParts 方法通过为你提供部分字符串来启用 DateTimeFormat 格式化程序生成的字符串的区域设置感知格式:

¥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:

js
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: "fractionalSecond", value: "000" },
  { type: "literal", value: " " },
  { type: "dayPeriod", value: "AM" },
];

现在,这些信息可以单独使用,并且可以以自定义方式再次格式化和连接。例如,使用 Array.prototype.map()箭头函数switch 语句模板文字Array.prototype.join()

¥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.join().

js
const dateString = formatter
  .formatToParts(date)
  .map(({ type, value }) => {
    switch (type) {
      case "dayPeriod":
        return `<em>${value}</em>`;
      default:
        return value;
    }
  })
  .join("");

这将在使用 formatToParts() 方法时强调白天的时间段。

¥This will emphasize the day period when using the formatToParts() method.

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

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

命名年份和混合日历

¥Named Years and Mixed calendars

在某些情况下,日历使用命名年份。例如,汉历和藏历使用 60 年 天干地支 的命名年份。这些年份通过与公历相应年份的关系来消除歧义。在这种情况下,当通常存在年份(包含 4 位公历年份)时,formatToParts() 的结果将包含 relatedYear 的条目,而不是 year 的条目。在包中设置 year 的条目(具有任何值)将产生 yearName 公历 relatedYear

¥In some cases, calendars use named years. Chinese and Tibetan calendars, for example, use a 60-year sexagenary cycle of named years. These years are disambiguated by relationship to corresponding years on the Gregorian calendar. When this is the case, the result of formatToParts() will contain an entry for relatedYear when a year would normally be present, containing the 4-digit Gregorian year, instead of an entry for year. Setting an entry in the bag for year (with any value) will yield both the and the yearName Gregorian relatedYear:

js
const opts = { year: "numeric", month: "numeric", day: "numeric" };
const df = new Intl.DateTimeFormat("zh-u-ca-chinese", opts);
df.formatToParts(Date.UTC(2012, 11, 17, 3, 0, 42));

// return value
[
  { type: "relatedYear", value: "2012" },
  { type: "literal", value: "年" },
  { type: "month", value: "十一月" },
  { type: "day", value: "4" },
];

如果包中未设置 year 选项(为任何值),则结果将仅包含 relatedYear

¥If the year option is not set in the bag (to any value), the result will include only the relatedYear:

js
const df = new Intl.DateTimeFormat("zh-u-ca-chinese");
df.formatToParts(Date.UTC(2012, 11, 17, 3, 0, 42));

// return value
[
  { type: "relatedYear", value: "2012" },
  { type: "literal", value: "年" },
  { type: "month", value: "十一月" },
  { type: "day", value: "4" },
];

在输出 year 的情况下,.format() 通常可能并排呈现这些:

¥In cases where the year would be output, .format() may commonly present these side-by-side:

js
const df = new Intl.DateTimeFormat("zh-u-ca-chinese", { year: "numeric" });
df.format(Date.UTC(2012, 11, 17, 3, 0, 42)); // 2012壬辰年

这也使得在 format 中混合区域设置和日历成为可能:

¥This also makes it possible to mix locale and calendar in both format:

js
const df = new Intl.DateTimeFormat("en-u-ca-chinese", { year: "numeric" });
const date = Date.UTC(2012, 11, 17, 3, 0, 42);
df.format(date); // 2012(ren-chen)

还有 formatToParts

¥And formatToParts:

js
const opts = { month: "numeric", day: "numeric", year: "numeric" };
const df = new Intl.DateTimeFormat("en-u-ca-chinese", opts);
const date = Date.UTC(2012, 11, 17, 3);
df.formatToParts(date);
// [
//   { type: 'month', value: '11' },
//   { type: 'literal', value: '/' },
//   { type: 'day', value: '4' },
//   { type: 'literal', value: '/' },
//   { type: 'relatedYear', value: '2012' }
// ]

规范

Specification
ECMAScript Internationalization API Specification
# sec-Intl.DateTimeFormat.prototype.formatToParts

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看