Get month name from Date

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

    If you don't mind extending the Date prototype (and there are some good reasons to not want to do this), you can actually come up with a very easy method:

    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"
    

    These functions will then apply to all javascript Date objects.

提交回复
热议问题