Intl.DateTimeFormat.prototype.formatRange()

Baseline 已广泛支持

此特性已发展成熟,可在多种设备和浏览器版本上使用。自 ⁨2021 年 8 月⁩ 起,它已在所有浏览器中可用。

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

试一试

const options1 = {
  weekday: "long",
  year: "numeric",
  month: "long",
  day: "numeric",
};
const options2 = { year: "2-digit", month: "numeric", day: "numeric" };

const startDate = new Date(Date.UTC(2007, 0, 10, 10, 0, 0));
const endDate = new Date(Date.UTC(2008, 0, 10, 11, 0, 0));

const dateTimeFormat = new Intl.DateTimeFormat("en", options1);
console.log(dateTimeFormat.formatRange(startDate, endDate));
// Expected output: "Wednesday, January 10, 2007 – Thursday, January 10, 2008"

const dateTimeFormat2 = new Intl.DateTimeFormat("en", options2);
console.log(dateTimeFormat2.formatRange(startDate, endDate));
// Expected output: "1/10/07 – 1/10/08"

语法

js
formatRange(startDate, endDate)

参数

startDate

日期范围的开始。可以是 DateTemporal.PlainDateTime 对象。此外,如果 DateTimeFormat 对象被配置为打印至少一个相关的日期部分,它也可以是 Temporal.PlainTimeTemporal.PlainDateTemporal.PlainYearMonthTemporal.PlainMonthDay 对象。

注意: Temporal.ZonedDateTime 对象总是会抛出 TypeError;请使用 Temporal.ZonedDateTime.prototype.toLocaleString() 或将其转换为 Temporal.PlainDateTime 对象。

endDate

日期范围的结束。必须与 startDate 具有相同的类型。

返回值

一个字符串,表示根据此 Intl.DateTimeFormat 对象的区域设置和格式化选项格式化的给定日期范围。如果开始日期和结束日期在输出精度上等效,则输出将只包含单个日期。

示例

Basic formatRange usage

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

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'

规范

规范
ECMAScript® 2026 国际化 API 规范
# sec-intl.datetimeformat.prototype.formatRange

浏览器兼容性

另见