Get month name from Date

前端 未结 30 2883
情歌与酒
情歌与酒 2020-11-22 00:16

How can I generate the name of the month (e.g: Oct/October) from this date object in JavaScript?

var objDate = new Date(\"10/11/2009\");
30条回答
  •  执念已碎
    2020-11-22 00:51

    Here's another one, with support for localization :)

    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']
        }
    };
    

    you can then easily add support for other languages:

    Date.locale.fr = {month_names: [...]};
    

提交回复
热议问题