如何格式化 JavaScript 日期 [英] How to format a JavaScript date
问题描述
在 JavaScript 中,如何将日期对象格式化为 10-Aug-2010
?
In JavaScript, how can I format a date object to print as 10-Aug-2010
?
推荐答案
对于自定义分隔的日期格式,你必须把日期(或时间)拉出来DateTimeFormat
对象(它是的一部分ECMAScript Internationalization API),然后手动创建一个字符串使用您想要的分隔符.
For custom-delimited date formats, you have to pull out the date (or time)
components from a DateTimeFormat
object (which is part of the
ECMAScript Internationalization API), and then manually create a string
with the delimiters you want.
为此,您可以使用 DateTimeFormat#formatToParts
.你可以解构数组,但这并不理想,因为数组输出取决于语言环境:
To do this, you can use DateTimeFormat#formatToParts
. You could
destructure the array, but that is not ideal, as the array output depends on the
locale:
{ // 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);
}
最好将格式数组映射到结果字符串:
Better would be to map a format array to resultant strings:
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 实现中存在一个错误.分钟和秒的前导零(这个错误被方法规避了以上).
You can also pull out the parts of a DateTimeFormat
one-by-one using
DateTimeFormat#format
, but note that when using this method, as of March
2020, there is a bug in the ECMAScript implementation when it comes to
leading zeros on minutes and seconds (this bug is circumvented by the approach
above).
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}`);
处理日期和时间时,通常值得使用库(例如.moment.js、luxon) 因为许多隐藏的复杂性领域.
When working with dates and times, it is usually worth using a library (eg. moment.js, luxon) because of the many hidden complexities of the field.
请注意,上述解决方案中使用的 ECMAScript 国际化 API在 IE10 中不支持 (0.03% 2 月份全球浏览器市场份额2020).
Note that the ECMAScript Internationalization API, used in the solutions above is not supported in IE10 (0.03% global browser market share in Feb 2020).
这篇关于如何格式化 JavaScript 日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!