Intl.DateTimeFormat.prototype.formatRangeToParts()

Intl.DateTimeFormat 实例的 formatRangeToParts() 方法返回一个特定于区域设置的标记数组,表示由该 Intl.DateTimeFormat 对象生成的格式化日期范围的每个部分。

¥The formatRangeToParts() method of Intl.DateTimeFormat instances returns an array of locale-specific tokens representing each part of the formatted date range produced by this Intl.DateTimeFormat object.

Try it

语法

¥Syntax

js
formatRangeToParts(startDate, endDate)

示例

¥Examples

基本 formatRangeToParts 用法

¥Basic formatRangeToParts usage

此方法接收两个 Date 并返回一个 Array 对象,其中包含表示格式化日期范围的每个部分的特定于区域设置的标记。

¥This method receives two Dates and returns an Array of objects containing the locale-specific tokens representing each part of the formatted date range.

注意:你的区域设置中显示的返回值可能与下面列出的不同。

¥Note: The return values shown in your locale may differ from those listed below.

js
const date1 = new Date(Date.UTC(1906, 0, 10, 10, 0, 0)); // Wed, 10 Jan 1906 10:00:00 GMT
const date2 = new Date(Date.UTC(1906, 0, 10, 11, 0, 0)); // Wed, 10 Jan 1906 11:00:00 GMT

const fmt = new Intl.DateTimeFormat("en", {
  hour: "numeric",
  minute: "numeric",
});

console.log(fmt.formatRange(date1, date2)); // '10:00 – 11:00 AM'

fmt.formatRangeToParts(date1, date2);
// [
//   { type: 'hour',      value: '10',  source: "startRange" },
//   { type: 'literal',   value: ':',   source: "startRange" },
//   { type: 'minute',    value: '00',  source: "startRange" },
//   { type: 'literal',   value: ' – ', source: "shared"     },
//   { type: 'hour',      value: '11',  source: "endRange"   },
//   { type: 'literal',   value: ':',   source: "endRange"   },
//   { type: 'minute',    value: '00',  source: "endRange"   },
//   { type: 'literal',   value: ' ',   source: "shared"     },
//   { type: 'dayPeriod', value: 'AM',  source: "shared"     }
// ]

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看