如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
当前回答
您可以简单地使用date . tolocaledatestring()并解析所需的日期作为参数
const事件=新的日期(日期。Utc (2012, 11,20,3,0,0)); Const选项={年:'numeric',月:'short',日:'numeric'}; console.log(事件。toLocaleDateString(“de-DE”,选项)); //期望输出:Donnerstag, 20。Dezember 2012 console.log(事件。toLocaleDateString(“en - us”,选项)); //美国格式 //如果你只想要这个月 console.log(事件。toLocaleDateString(undefined, {month: 'short'})); console.log(事件。toLocaleDateString(undefined, {month: 'long'}));
您可以在Firefox文档中找到更多信息
其他回答
如果我们需要传递输入,那么我们需要使用以下方式
输入:“2020-12-28”
代码:
new Date('2020-12-28').toLocaleString('en-us',{month:'short', year:'numeric'})
输出:“2020年12月”
如果你不想使用一个外部库,或者存储一个月份名称的数组,或者如果ECMAScript国际化API因为浏览器兼容性而不够好,你可以通过从日期输出中提取信息来实现:
var now = new Date();
var monthAbbrvName = now.toDateString().substring(4, 7);
这将为您提供缩写的月份名称,例如october。我相信日期将以各种格式出现,这取决于初始化和您的地区,因此请查看toDateString()返回的内容,并基于此重新计算您的substring()值。
这是一种不依赖于硬编码数组并支持多个区域设置的方法。
如果你需要一个完整的数组:
var monthsLocalizedArray = function(locale) {
var result = [];
for(var i = 0; i < 12; i++) {
result.push(new Date(2010,i).toLocaleString(locale,{month:"long"}));
}
return result;
};
用法:
console.log(monthsLocalizedArray('en')); // -> ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
console.log(monthsLocalizedArray('bg')); // -> ["януари", "февруари", "март", "април", "май", "юни", "юли", "август", "септември", "октомври", "ноември", "декември"]
如果你只需要一个选定的月份(更快):
var monthLocalizedString = function(month, locale) {
return new Date(2010,month).toLocaleString(locale,{month:"long"});
};
用法:
console.log(monthLocalizedString(1, 'en')); // -> February
console.log(monthLocalizedString(1, 'bg')); // -> февруари
console.log(monthLocalizedString(1, 'de')); // -> Februar
经过测试,在Chrome和IE 11上运行良好。在mozilla上需要做一些修改,因为它返回整个日期。
这是另一个,支持本地化:)
Date.prototype.getMonthName = function(lang) {
lang = lang && (lang in Date.locale) ? lang : 'en';
return Date.locale[lang].month_names[this.getMonth()];
};
Date.prototype.getMonthNameShort = function(lang) {
lang = lang && (lang in Date.locale) ? lang : 'en';
return Date.locale[lang].month_names_short[this.getMonth()];
};
Date.locale = {
en: {
month_names: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
month_names_short: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
}
};
然后,您可以轻松地添加对其他语言的支持:
Date.locale.fr = {month_names: [...]};
Date.prototype.getMonthName = function() {
var monthNames = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
return monthNames[this.getMonth()];
}
它可以被用作
var month_Name = new Date().getMonthName();