小编典典

如何格式化 JavaScript 日期

javascript

在 JavaScript 中,如何格式化日期对象以打印为10-Aug-2010?


阅读 286

收藏
2022-01-24

共1个答案

小编典典

对于自定义分隔的日期格式,您必须从DateTimeFormat对象(这是 ECMAScript 国际化 API的一部分)中提取日期(或时间)组件,然后手动创建带有所需分隔符的字符串。

为此,您可以使用DateTimeFormat#formatToParts. 您可以解构数组,但这并不理想,因为数组输出取决于语言环境:

{ // example 1
   let f = new Intl.DateTimeFormat('en');
   let a = f.formatToParts();
   console.log(a);
}
{ // example 2
   let f = new Intl.DateTimeFormat('hi');
   let a = f.formatToParts();
   console.log(a);
}

最好将格式数组映射到结果字符串:

function join(t, a, s) {
   function format(m) {
      let f = new Intl.DateTimeFormat('en', m);
      return f.format(t);
   }
   return a.map(format).join(s);
}

let a = [{day: 'numeric'}, {month: 'short'}, {year: 'numeric'}];
let s = join(new Date, a, '-');
console.log(s);

DateTimeFormat您也可以使用 逐一 拉出部分DateTimeFormat#format,但请注意,使用此方法时,截至 2020 年 3 月,ECMAScript 实现中存在一个错误,即分钟和秒的前导零(此错误被上述方法规避)。

let d = new Date(2010, 7, 5);
let ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d);
let mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(d);
let da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d);
console.log(`${da}-${mo}-${ye}`);

在处理日期和时间时,通常值得使用库(例如 moment.jsluxon),因为该领域有许多隐藏的复杂性。

请注意, IE10不支持上述解决方案中使用的 ECMAScript 国际化 API (2020 年 2 月全球浏览器市场份额为0.03% )。

2022-01-24