如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
当前回答
这是另一个,支持本地化:)
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: [...]};
其他回答
不幸的是,提取月份名称的最佳方法是从UTCString表示中提取:
Date.prototype.monthName = function() {
return this.toUTCString().split(' ')[2]
};
d = new Date();
//=> Thu Mar 06 2014 23:05:21 GMT+0000 (GMT)
d.monthName();
//=> 'Mar'
如果您不介意扩展Date原型(并且有一些很好的理由不想这样做),您实际上可以提出一个非常简单的方法:
Date.prototype.monthNames = [
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
];
Date.prototype.getMonthName = function() {
return this.monthNames[this.getMonth()];
};
Date.prototype.getShortMonthName = function () {
return this.getMonthName().substr(0, 3);
};
// usage:
var d = new Date();
alert(d.getMonthName()); // "October"
alert(d.getShortMonthName()); // "Oct"
这些函数将应用于所有javascript Date对象。
只需要编写一个简单的toLocaleString包装器:
函数 LocalDate(locale) { this.locale = locale; } LocalDate.prototype.getMonthName = function(date) { return date.toLocaleString(this.locale,{month:“long”}); }; var objDate = new Date(“10/11/2009”); var localDate = new LocalDate(“en”); console.log(localDate.getMonthName(objDate)); localdate.locale = “ru”; console.log(localDate.getMonthName(objDate)); localdate.locale = “zh”; console.log(localDate.getMonthName(objDate));
你可以使用或不使用当地语言翻译
创造价值“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(朗,{ 月:“长” })) }
如果你不想使用一个外部库,或者存储一个月份名称的数组,或者如果ECMAScript国际化API因为浏览器兼容性而不够好,你可以通过从日期输出中提取信息来实现:
var now = new Date();
var monthAbbrvName = now.toDateString().substring(4, 7);
这将为您提供缩写的月份名称,例如october。我相信日期将以各种格式出现,这取决于初始化和您的地区,因此请查看toDateString()返回的内容,并基于此重新计算您的substring()值。