如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
当前回答
在IE 11, Chrome, Firefox上测试
const dt = new Date(); Const locale = navigator。语言!= undefined ?导航器。[0]: navigator.language; const fullMonth = dt。toLocaleDateString(区域设置,{month: 'long'}); console.log (fullMonth);
其他回答
你可以使用或不使用当地语言翻译
创造价值“2009年10月11日”
const objDate =新日期("10/11/2009"); const月=[‘简’,2月,3月,4月,“可能”,“君”,7月,8月,9月,10月,11月,12月的) if (objDate !== '无效日期' && !isNaN(objDate)) { console.log(objDate.getDate() + ' ' + months[objDate.getMonth()] + ' ' + objDate.getFullYear())) }
ECMAScript国际化API将month转换为本地语言(例如:october 11)
const convertDate = new Date('10/11/2009') Const lang = 'fr' // de, es, ch if (convertDate !== '无效日期' && !isNaN(convertDate)) { console.log(convertDate. getdate () + ' ' + convertDate. log)toLocaleString(朗,{ 月:“长” })) }
这是另一个,支持本地化:)
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: [...]};
也可以这样做:
var x = new Date().toString().split(' ')[1]; // "Jul"
在IE 11, Chrome, Firefox上测试
const dt = new Date(); Const locale = navigator。语言!= undefined ?导航器。[0]: navigator.language; const fullMonth = dt。toLocaleDateString(区域设置,{month: 'long'}); console.log (fullMonth);
如果我们需要传递输入,那么我们需要使用以下方式
输入:“2020-12-28”
代码:
new Date('2020-12-28').toLocaleString('en-us',{month:'short', year:'numeric'})
输出:“2020年12月”