在 JavaScript 如何将格式化日期对象打印成10-Aug-2010?* z8 z" q4 t w9 L
1 D6 L. [, f- }4 M, d( I解决方案: " O& d6 H) y6 @ 对于自定义分隔的日期格式,您必须从DateTimeFormat对象(这是 ECMAScript 国际化 API提取日期(或时间)组件,然后手动创建带有所需分隔符的字符串。' B7 f' K7 K4 S, g
为此,您可以使用它DateTimeFormat#formatToParts.由于数组输出取决于语言环境: 7 r8 Z; o7 z( @: _4 v3 H2 p
{ // 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);}$ O! g- ?7 H; z: Q2 b% D# v
最好将格式数组映射到结果字符串:' K5 j5 z, s0 [" m- w
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); 4 j$ P B6 v8 G; p: E$ N
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}`);6 y8 ~+ `) g7 o# J4 F$ J
通常值得使用库(如 moment.js、luxon),因为这个领域有很多隐藏的复杂性。) a* ~# J, I$ f* D$ a, R
请注意,IE 10不支持上述解决方案中使用的 ECMAScript 国际化 API (2020年 2 月全球浏览器市场份额0.03% )。