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


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

Intl.DateTimeFormat.prototype.formatToParts() 方法是 JavaScript 中的一個內置方法,它允許對 DateTimeFormat 格式化程序生成的字符串進行 locale-aware 格式化。

用法:

dateTimeFormat.formatToParts( date )

參數:此方法接受如上所述和以下描述的單個參數:

  • date:它是一個可選參數,它保存要格式化的日期。

返回值:此方法返回一個對象數組,其中包含部分格式化的日期。

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



範例1:


let geeks = {month:'numeric', day:'numeric', year:"numeric"};
let result =  new Intl.DateTimeFormat("en-u-ca-chinese", geeks);
let datetime = Date.UTC(2012, 11, 17, 3);
let val = result.formatToParts(datetime);
console.log(val[0]);
console.log(val[1]);
console.log(val[2]);
console.log(val[3]);

輸出:

Object { type:"month", value:"11" }
Object { type:"literal", value:"/" }
Object { type:"day", value:"5" }
Object { type:"literal", value:"/" }

範例2:


let date = new Intl.DateTimeFormat("hi");
let val = date.formatToParts(Date.UTC(2012, 11, 17, 3, 0, 42));
console.log(val[0]);
console.log(val[1]);
console.log(val[2]);
console.log(val[3]);
console.log(val[4]);

輸出:

Object { type:"day", value:"17" }
Object { type:"literal", value:"/" }
Object { type:"month", value:"12" }
Object { type:"literal", value:"/" }
Object { type:"year", value:"2012" }

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

  • 穀歌瀏覽器
  • Edge
  • Firefox
  • Opera
  • Safari

相關用法


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