Intl.DateTimeFormat.prototype.formatRange()
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-
日期範圍的開始。可以是
Date或Temporal.PlainDateTime物件。此外,如果DateTimeFormat物件被配置為列印至少一個相關的日期部分,它也可以是Temporal.PlainTime、Temporal.PlainDate、Temporal.PlainYearMonth或Temporal.PlainMonthDay物件。注意:
Temporal.ZonedDateTime物件總是會丟擲TypeError;請使用Temporal.ZonedDateTime.prototype.toLocaleString()或將其轉換為Temporal.PlainDateTime物件。 endDate-
日期範圍的結束。必須與
startDate具有相同的型別。
返回值
一個字串,表示根據此 Intl.DateTimeFormat 物件的區域設定和格式化選項格式化的給定日期範圍。如果開始日期和結束日期在輸出精度上等效,則輸出將只包含單個日期。
示例
Basic formatRange usage
此方法接收兩個 Date 物件,並根據例項化 Intl.DateTimeFormat 時提供的 locale 和 options 以最簡潔的方式格式化日期範圍。
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 |
瀏覽器相容性
載入中…