Get month name from Date

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

    Some common easy process from date object can be done by this.

    var monthNames = ["January", "February", "March", "April", "May", "June",
      "July", "August", "September", "October", "November", "December"
    ];
    var monthShortNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
      "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    ];
    
    function dateFormat1(d) {
      var t = new Date(d);
      return t.getDate() + ' ' + monthNames[t.getMonth()] + ', ' + t.getFullYear();
    }
    
    function dateFormat2(d) {
      var t = new Date(d);
      return t.getDate() + ' ' + monthShortNames[t.getMonth()] + ', ' + t.getFullYear();
    }
    
    console.log(dateFormat1(new Date()))
    console.log(dateFormat2(new Date()))

    Or you can make date prototype like

    Date.prototype.getMonthName = function() {
      var monthNames = ["January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"
      ];
      return monthNames[this.getMonth()];
    }
    
    
    Date.prototype.getFormatDate = function() {
      var monthNames = ["January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"
      ];
      return this.getDate() + ' ' + monthNames[this.getMonth()] + ', ' + this.getFullYear();
    }
    
    
    console.log(new Date().getMonthName())
    console.log(new Date().getFormatDate())

    Ex:

    var dateFormat3 = new Date().getMonthName(); # March

    var dateFormat4 = new Date().getFormatDate(); # 16 March, 2017

提交回复
热议问题