3 回答

TA贡献1785条经验 获得超4个赞
较短版本:
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
const d = new Date();
document.write("The current month is " + monthNames[d.getMonth()]);

TA贡献1799条经验 获得超8个赞
现在可以使用ECMAScript国际化API来实现这一点:
const date = new Date(2009, 10, 10); // 2009-11-10
const month = date.toLocaleString('en-us', { month: 'long' });
console.log(month);
long使用月份全名,short为短名,和narrow一个更小的版本,例如字母中的第一个字母。
您可以将区域设置更改为en-us任何您喜欢的,它将使用正确的名称,该语言/国家。
带着toLocaleString每次都必须传递区域和选项。如果要在多个不同的日期使用相同的区域设置信息和格式设置选项,则可以使用Intl.DateTimeFormat相反:
if (typeof Intl == 'object' && typeof Intl.DateTimeFormat == 'function') {
var formatter = new Intl.DateTimeFormat("fr", {
month: "short"
}),
month1 = formatter.format(new Date()),
month2 = formatter.format(new Date(2003, 5, 12));
// current month in French and "juin".
console.log(month1 + " and " + month2);
}
添加回答
举报