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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。