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 |
浏览器兼容性
加载中…