Javascript 无法将日期格式化为工作日后跟天



使用JavaScript内置In intl.dateTimeFormat进行格式化日期时,如果您提供格式{weekday : 'short', day 'numeric'},则将重新安排两者,并始终为工作日提供一天。

供参考:

console.log(new Intl.DateTimeFormat('en-US', {
  weekday: 'short',
  day: 'numeric'
}).format(new Date));

我希望Fri 3,但我会收到3 Fri

我是在错误地使用它还是这是一个错误?

我尝试过的即时解决方法是要在工作日中格式化,然后就在一天,然后添加两个可行的方法,但这对我的项目不理想。

en-US是整日/工作日,=>使用 en-GB

let
  date3may = new Date('May 3, 2019 15:24:00'),
  Options  = {weekday:'short', day:'numeric'};
console.log(new Intl.DateTimeFormat('en-GB', Options).format(date3may));

输出的顺序由语言环境定义。

如果要避免串联,可以使用其他英语语言环境,例如en-AU

    var date = new Date();
    console.log(new Intl.DateTimeFormat('en-AU', {
      weekday: 'short',
      day: 'numeric'
    }).format(date));

有关所有可能地区的列表,您可以在此处(MDN(或此处(stackoverflow(。

根据MDN,以一致的结果实现所需的正确方法是使用Intl.DateTimeFormat.prototype.formatToParts()方法,然后手动操纵给定的数组。

我的第一种方法如下:

let date = new Date();
let order = ['weekday', 'day'];
new Intl.DateTimeFormat('en-US', {
    weekday: 'short',
    day: 'numeric'
}).formatToParts(date).filter((elem) => {
    return (elem.type !== 'literal');
}).sort((a, b) => {
    // SET ORDER
    let i = 0;
    a.index = -1;
    b.index = -1;
    order.forEach((type) => {
       if (a.type === type) {
           a.index = i;
       }
       if (b.type === type) {
           b.index = i;
       }
       i++;
    });
    return (a.index - b.index);
}).map(({type, value}) => {
    // MODIFY ELEMENT
    switch (type) {
        default : return (value);
    }
}).reduce((string, part) => string + ' ' + part);

最新更新