Intl.DateTimeFormat.prototype.formatRange()

Intl.DateTimeFormat 实例的 formatRange() 方法根据实例化此 Intl.DateTimeFormat 对象时提供的区域设置和选项,以最简洁的方式格式化日期范围。

¥The formatRange() method of Intl.DateTimeFormat instances formats a date range in the most concise way based on the locales and options provided when instantiating this Intl.DateTimeFormat object.

Try it

语法

¥Syntax

js
formatRange(startDate, endDate)

参数

¥Parameters

startDate

代表日期范围开始的 Date 对象。

endDate

代表日期范围结束的 Date 对象。

返回值

¥Return value

表示给定日期范围的字符串,该日期范围根据此 Intl.DateTimeFormat 对象的区域设置和格式选项进行格式化。

¥A string representing the given date range formatted according to the locale and formatting options of this Intl.DateTimeFormat object.

示例

¥Examples

基本格式范围使用

¥Basic formatRange usage

该方法接收两个 Date,并根据实例化 Intl.DateTimeFormat 时提供的 localeoptions,以最简洁的方式格式化日期范围。

¥This method receives two Dates and formats the date range in the most concise way based on the locale and options provided when instantiating Intl.DateTimeFormat.

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 date3 = new Date(Date.UTC(1906, 0, 20, 10, 0, 0)); // Sat, 20 Jan 1906 10:00:00 GMT

const fmt1 = new Intl.DateTimeFormat("en", {
  year: "2-digit",
  month: "numeric",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
});
console.log(fmt1.format(date1)); // '1/10/06, 10:00 AM'
console.log(fmt1.formatRange(date1, date2)); // '1/10/06, 10:00 – 11:00 AM'
console.log(fmt1.formatRange(date1, date3)); // '1/10/06, 10:00 AM – 1/20/07, 10:00 AM'

const fmt2 = new Intl.DateTimeFormat("en", {
  year: "numeric",
  month: "short",
  day: "numeric",
});
console.log(fmt2.format(date1)); // 'Jan 10, 1906'
console.log(fmt2.formatRange(date1, date2)); // 'Jan 10, 1906'
console.log(fmt2.formatRange(date1, date3)); // 'Jan 10 – 20, 1906'

规范

Specification
ECMAScript Internationalization API Specification
# sec-intl.datetimeformat.prototype.formatRange

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看