如何将Javascript的Date
对象格式化为字符串?(最好格式为:10-Aug-2010
)
要自定义分隔符的日期格式,您需要从DateTimeFormat
对象中提取日期(或时间)组件,然后使用所需的分隔符手动创建字符串。
为此,您可以使用DateTimeFormat#formatToParts
方法。虽然数组输出取决于区域设置,但将其解构并不是最佳选择。
更好的方法是将格式数组映射到结果字符串:
function join(date, options, separator) {
function format(option) {
let formatter = new Intl.DateTimeFormat('en', option);
return formatter.format(date);
}
return options.map(format).join(separator);
}
let options = [{day: 'numeric'}, {month: 'short'}, {year: 'numeric'}];
let joined = join(new Date(), options, '-');
console.log(joined);
您还可以使用DateTimeFormat#format
逐项提取DateTimeFormat
的部分,但请注意,自2020年3月起,在使用此方法时,ECMAScript实现中存在一个关于分钟和秒数前导零的 bug(通过上述方法绕过)。
let date = new Date(2010, 7, 5);
let year = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(date);
let month = new Intl.DateTimeFormat('en', { month: 'short' }).format(date);
let day = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(date);
console.log(`${day}-${month}-${year}`);
在处理日期和时间时,通常值得使用库(例如luxon、date-fns、moment.js 不推荐用于新项目),因为该领域有许多隐藏的复杂性。
请注意,上述解决方案中使用的ECMAScript Internationalization API(在解决方案上方)在IE10中不受支持(2020年2月全球浏览器市场份额为0.03%)。