对于自定义分隔的日期格式,必须拉出日期(或时间)
要做到这一点,您可以使用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
,但请注意,使用此方法时,截至3月
2020年,ECMAScript实现中有a bug个
分钟和秒的前导零(该方法绕过了此错误
(上图).
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}`);
当处理日期和时间时,通常值得使用库(例如.
请注意,在上述解决方案中使用的ECMAScript国际化API