当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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:




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));

输出:

范例2:


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() 方法支持的浏览器如下:

  • 谷歌浏览器
  • Firefox
  • Opera
  • Edge
  • IE
  • Safari



相关用法


注:本文由纯净天空筛选整理自SHUBHAMSINGH10大神的英文原创作品 JavaScript | Intl.DateTimeFormat.prototype.formatRange() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。