當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Javascript Intl.DateTimeFormat.prototype.formatRangeToParts()用法及代碼示例

Intl.DateTimeFormat.prototype.formatRangeToParts() 方法是 JavaScript 中的一個內置方法,用於允許 locale-specific 標記代表 DateTimeFormat 格式化程序生成的格式化日期範圍的每個部分。

用法:

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

參數:此方法接受上麵提到和下麵描述的兩個參數:

  • startDate:此參數保存範圍的開始日期。
  • endDate:此參數保存範圍的結束日期。

下麵的例子說明了 JavaScript 中的 Intl.DateTimeFormat.prototype.formatRangeToParts() 方法:

範例1:



Javascript


const startDate = new Date(Date.UTC(1997, 5, 30, 3, 3, 3));
const endDate = new Date(Date.UTC(2073, 7, 6, 11, 0, 0));
 
let result = new Intl.DateTimeFormat("hi", {
    hour:'numeric',
    minute:'numeric'
});
 
console.log(result.formatRange(startDate, endDate));
let val = result.formatRangeToParts(startDate, endDate);
console.log(val[0]);
console.log(val[2]);
console.log(val[3]);
console.log(val[8]);

輸出:

"30/6/1997, 8:33 am - 6/8/2073, 4:30 pm"
Object { type:"day", value:"30", source:"startRange" }
Object { type:"month", value:"6", source:"startRange" }
Object { type:"literal", value:"/", source:"startRange" }
Object { type:"minute", value:"33", source:"startRange" }

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

輸出:

"month" "6" "startRange"
"literal" "/" "startRange"
"day" "30" "startRange"
"literal" "/" "startRange"
"year" "1997" "startRange"
"literal" ", " "startRange"
"hour" "8" "startRange"
"literal" ":" "startRange"
"minute" "33" "startRange"
"literal" " " "startRange"
"dayPeriod" "AM" "startRange"
"literal" " - " "shared"
"month" "8" "endRange"
"literal" "/" "endRange"
"day" "6" "endRange"
"literal" "/" "endRange"
"year" "2073" "endRange"
"literal" ", " "endRange"
"hour" "4" "endRange"
"literal" ":" "endRange"
"minute" "30" "endRange"
"literal" " " "endRange"
"dayPeriod" "PM" "endRange"

支持的瀏覽器: Intl.DateTimeFormat.prototype.formatRangeToParts() 方法支持的瀏覽器如下:

  • 穀歌瀏覽器
  • 網頁視圖安卓
  • chrome 安卓
  • Opera 安卓




相關用法


注:本文由純淨天空篩選整理自SHUBHAMSINGH10大神的英文原創作品 JavaScript | Intl.DateTimeFormat.prototype.formatRangeToParts() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。