Get month name from Date

前端 未结 30 2944
情歌与酒
情歌与酒 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:54

    Here's a way that does not depend on a hard-coded array and supports multiple locales.

    If you need a whole array:

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

    Usage:

    console.log(monthsLocalizedArray('en')); // -> ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
    console.log(monthsLocalizedArray('bg')); // -> ["януари", "февруари", "март", "април", "май", "юни", "юли", "август", "септември", "октомври", "ноември", "декември"]
    

    If you need only a selected month (faster):

    var monthLocalizedString = function(month, locale) {
        return new Date(2010,month).toLocaleString(locale,{month:"long"});
    };
    

    Usage:

    console.log(monthLocalizedString(1, 'en')); // -> February
    console.log(monthLocalizedString(1, 'bg')); // -> февруари
    console.log(monthLocalizedString(1, 'de')); // -> Februar
    

    Tested and works fine on Chrome and IE 11. On mozilla some modifications are needed, because it returns the whole date.

提交回复
热议问题