📌  相关文章
📜  JavaScript | Intl.DateTimeFormat.prototype.formatRange() 方法

📅  最后修改于: 2022-05-13 01:56:18.993000             🧑  作者: Mango

JavaScript | Intl.DateTimeFormat.prototype.formatRange() 方法

Intl.DateTimeFormat.prototype.formatRange()方法是 JavaScript 中的内置方法,用于根据实例化 Intl.DateTimeFormat 对象时提供的语言环境和选项以最简洁的方式格式化日期范围。
句法:

Intl.DateTimeFormat.prototype.formatRange(startDate, endDate)

参数:此方法接受上面提到的两个参数,如下所述:

  • startDate:此参数保存范围的开始日期。
  • endDate:此参数保存范围的结束日期。

下面的示例说明了 JavaScript 中的Intl.DateTimeFormat.prototype.formatRange() 方法
示例 1:

javascript
const geeks1 = { weekday: 'long', year: 'numeric',
                 month: 'long', day: 'numeric' };
const geeks2 = { year: '2-digit', month: 'numeric',
                 day: 'numeric' };
 
const startDate = new Date(Date.UTC(1997, 5, 30, 3, 3, 3));
const endDate = new Date(Date.UTC(2073, 7, 6, 11, 0, 0));
 
const dateTime = new Intl.DateTimeFormat('en', geeks1);
console.log(dateTime.formatRange(startDate, endDate));
 
const dateTime1 = new Intl.DateTimeFormat('hi', geeks1);
console.log(dateTime1.formatRange(startDate, endDate));
 
const dateTime2 = new Intl.DateTimeFormat('en', geeks2);
console.log(dateTime2.formatRange(startDate, endDate));
 
const dateTime3 = new Intl.DateTimeFormat('hi', geeks2);
console.log(dateTime3.formatRange(startDate, endDate));


javascript
let geek1 = new Date(Date.UTC(1997, 5, 30, 10, 0, 0));
let geek2 = new Date(Date.UTC(2020, 2, 26, 11, 0, 0));
let geek3 = new Date(Date.UTC(2073, 6, 23, 10, 0, 0));
 
let result1 = new Intl.DateTimeFormat("en", {
    year: '2-digit',
    month: 'numeric',
    day: 'numeric',
    hour: 'numeric',
    minute: 'numeric'
});
console.log(result1.format(geek1));
console.log(result1.formatRange(geek1, geek2));
console.log(result1.formatRange(geek1, geek3));
 
let result2 = new Intl.DateTimeFormat("hi", {
    year: 'numeric',
    month: 'short',
    day: 'numeric'
});
console.log(result2.format(geek1));
console.log(result2.formatRange(geek1, geek2));
console.log(result2.formatRange(geek1, geek3));


输出:

示例 2:

javascript

let geek1 = new Date(Date.UTC(1997, 5, 30, 10, 0, 0));
let geek2 = new Date(Date.UTC(2020, 2, 26, 11, 0, 0));
let geek3 = new Date(Date.UTC(2073, 6, 23, 10, 0, 0));
 
let result1 = new Intl.DateTimeFormat("en", {
    year: '2-digit',
    month: 'numeric',
    day: 'numeric',
    hour: 'numeric',
    minute: 'numeric'
});
console.log(result1.format(geek1));
console.log(result1.formatRange(geek1, geek2));
console.log(result1.formatRange(geek1, geek3));
 
let result2 = new Intl.DateTimeFormat("hi", {
    year: 'numeric',
    month: 'short',
    day: 'numeric'
});
console.log(result2.format(geek1));
console.log(result2.formatRange(geek1, geek2));
console.log(result2.formatRange(geek1, geek3));

输出:

支持的浏览器: Intl.DateTimeFormat.prototype.formatRange() 方法支持的浏览器如下:

  • 谷歌浏览器 76 及以上
  • 火狐 91 及以上
  • Opera 63 及以上
  • Edge 79 及以上
  • Safari 14.1 及更高版本