如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?

var objDate = new Date("10/11/2009");

当前回答

另一种格式化日期的方法

new Date().toLocaleString('en-us',{month:'long', year:'numeric', day:'numeric'}) //output: "May 21, 2019"

其他回答

不幸的是,提取月份名称的最佳方法是从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 . 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文档中找到更多信息

这是另一个,支持本地化:)

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: [...]};

另一种格式化日期的方法

new Date().toLocaleString('en-us',{month:'long', year:'numeric', day:'numeric'}) //output: "May 21, 2019"

如果您不介意扩展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对象。