Get month name from Date

前端 未结 30 2917
情歌与酒
情歌与酒 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 01:03

    It can be done as follows too:

    var x = new Date().toString().split(' ')[1];    // "Jul"
    
    0 讨论(0)
  • 2020-11-22 01:04

    You could just simply use Date.toLocaleDateString() and parse the date wanted as parameter

    const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
    
    const options = {  year: 'numeric', month: 'short', day: 'numeric' };
    
    console.log(event.toLocaleDateString('de-DE', options));
    // expected output: Donnerstag, 20. Dezember 2012
    
    console.log(event.toLocaleDateString('en-US', options));
    // US format 
    
    
    // In case you only want the month
    console.log(event.toLocaleDateString(undefined, { month: 'short'}));
    console.log(event.toLocaleDateString(undefined, { month: 'long'}));

    You can find more information in the Firefox documentation

    0 讨论(0)
  • 2020-11-22 01:05

    Store the names in a array and look up by the index of the month.

    var month=new Array(12);
    month[0]="January";
    month[1]="February";
    month[2]="March";
    month[3]="April";
    month[4]="May";
    month[5]="June";
    month[6]="July";
    month[7]="August";
    month[8]="September";
    month[9]="October";
    month[10]="November";
    month[11]="December";
    
    document.write("The current month is " + month[d.getMonth()]);
    

    JavaScript getMonth() Method

    0 讨论(0)
  • 2020-11-22 01:06

    Just extending on the many other excellent answers - if you are using jQuery - you could just do something like

    $.fn.getMonthName = function(date) {
    
        var monthNames = [
        "January", "February", "March",
        "April", "May", "June",
        "July", "August", "September",
        "October", "November", "December"
        ];
    
        return monthNames[date.getMonth()];
    
    };
    

    where date is equal to the var d = new Date(somevalue). The primary advantage of this is per @nickf said about avoiding the global namespace.

    0 讨论(0)
  • 2020-11-22 01:07
    Date.prototype.getMonthName = function() {
        var monthNames = [ "January", "February", "March", "April", "May", "June", 
                           "July", "August", "September", "October", "November", "December" ];
        return monthNames[this.getMonth()];
    }
    

    It can be used as

    var month_Name = new Date().getMonthName();
    
    0 讨论(0)
  • 2020-11-22 01:10

    Tested on IE 11, Chrome, Firefox

    const dt = new Date();
    const locale = navigator.languages != undefined ? navigator.languages[0] : navigator.language;
    const fullMonth = dt.toLocaleDateString(locale, {month: 'long'});
    console.log(fullMonth);

    0 讨论(0)
提交回复
热议问题