如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
当前回答
对我来说,这是最佳解,
对于TypeScript也一样
const env = process.env.REACT_APP_LOCALE || 'en';
const namedMonthsArray = (index?: number): string[] | string => {
const months = [];
for (let month = 0; month <= 11; month++) {
months.push(
new Date(new Date('1970-01-01').setMonth(month))
.toLocaleString(env, {
month: 'long',
})
.toString(),
);
}
if (index) {
return months[index];
}
return months;
};
输出是
["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
其他回答
如果你赶时间……那就给你!
const date = new Date(Date.now());
date.toLocaleString('en-US', {month: 'short'}); // {month:'long'}
预期产出:“四月”
您可以使用datejs来实现这一点。检查格式说明符,MMMM给出了月份的名称:
var objDate = new Date("10/11/2009");
document.write(objDate.toString("MMMM"));
datejs本地化了超过150个locale !在这里看到的
如果你不想使用一个外部库,或者存储一个月份名称的数组,或者如果ECMAScript国际化API因为浏览器兼容性而不够好,你可以通过从日期输出中提取信息来实现:
var now = new Date();
var monthAbbrvName = now.toDateString().substring(4, 7);
这将为您提供缩写的月份名称,例如october。我相信日期将以各种格式出现,这取决于初始化和您的地区,因此请查看toDateString()返回的内容,并基于此重新计算您的substring()值。
如果你正在使用jQuery,你可能也在使用jQuery UI,这意味着你可以使用$.datepicker. formatdate()。
$.datepicker.setDefaults( $.datepicker.regional[ "nl" ] ); // dutch
$.datepicker.formatDate( "dd MM yy", objDate );
date对象中一些常见的简单处理可以通过它来完成。
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var monthShortNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; function dateFormat1(d) { var t = new Date(d); return t.getDate() + ' ' + monthNames[t.getMonth()] + ', ' + t.getFullYear(); } function dateFormat2(d) { var t = new Date(d); return t.getDate() + ' ' + monthShortNames[t.getMonth()] + ', ' + t.getFullYear(); } console.log(dateFormat1(new Date())) console.log(dateFormat2(new Date()))
或者你可以制作日期原型
Date.prototype.getMonthName = function() { var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; return monthNames[this.getMonth()]; } Date.prototype.getFormatDate = function() { var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; return this.getDate() + ' ' + monthNames[this.getMonth()] + ', ' + this.getFullYear(); } console.log(new Date().getMonthName()) console.log(new Date().getFormatDate())
Ex:
var dateentt3新日期()#发情
var dateFormat4 = new Date().getFormatDate();# 16 三月, 2017