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


JavaScript Intl DateTimeFormat()用法及代码示例

JavaScript Intl.DateTimeFormat 构造函数用于创建 Intl.DateTimeFormat 对象。可以使用或不使用 new 关键字调用此构造函数

用法:

Intl.DateTimeFormat(loc, opt)
new Intl.DateTimeFormat(loc, opt)

参数:该构造函数有两个方法,并且都是可选的。

  • loc: 这是一个字符串或字符串数组,允许使用以下值:
    • nu:它指定要遵循的编号系统
    • ca:它指定要遵循的日历
    • hc:它指定要遵循的小时周期格式
  • opt: 该参数包含其他属性,例如日期风格,时间风格,日间、纪元等等。

返回:这将返回一个新的 DateTimeFormat 对象,其属性根据是否使用 new 关键字调用而有所不同。

下面的示例说明了 JavaScript Intl DateTimeFormat() 构造函数:

示例 1:在此示例中,我们将创建一个 DateTimeFormat 对象并使用它来格式化日期对象。

Javascript


const time = new Intl.DateTimeFormat("en", { 
    timeStyle: "short", 
    dateStyle: "short"
}) 
var val = new Date(); 
console.log(time.format(val));

输出:使用 format 方法对日期变量进行格式化

4/3/23, 2:11 PM

示例 2:在此示例中,我们将使用构造函数格式化 Date 对象。

Javascript


var val = new Date(); 
console.log(new Intl.DateTimeFormat("en",{ 
    hour: "2-digit", 
    month: "numeric", 
    hourCycle: "h23", 
    dayPeriod: "long", 
    timeZone: "GMT", 
}).format(val));

输出:

4, 08

支持的浏览器:

  • Chrome
  • Edge
  • Firefox
  • Opera
  • Safari

我们有完整的 JavaScript Intl 方法列表可供检查,请阅读 JavaScript Intl Reference 文章。


相关用法


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