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

瀏覽器相容性

另見