Javascript 无法将日期格式化为工作日后跟天
Javascript can't format the date into a weekday followed by day
当使用 javascript 内置的 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));
有关所有可能语言环境的列表,您可以参考 here (MDN) or here (Whosebug)。
根据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);
当使用 javascript 内置的 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));
有关所有可能语言环境的列表,您可以参考 here (MDN) or here (Whosebug)。
根据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);