如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?

var objDate = new Date("10/11/2009");

当前回答

如果您不想使用时刻,并希望显示月份名称-

.config($mdDateLocaleProvider) {
    $mdDateLocaleProvider.formatDate = function(date) {      
      if(date !== null) {
        if(date.getMonthName == undefined) {
          date.getMonthName = function() {
            var monthNames = [ "January", "February", "March", "April", "May", "June", 
            "July", "August", "September", "October", "November", "December" ];
            return monthNames[this.getMonth()];
          }
        }        
        var day = date.getDate();
        var monthIndex = date.getMonth();
        var year = date.getFullYear();
        return day + ' ' + date.getMonthName() + ' ' + year;
      }
    };
  }

其他回答

如果你正在使用jQuery,你可能也在使用jQuery UI,这意味着你可以使用$.datepicker. formatdate()。

$.datepicker.setDefaults( $.datepicker.regional[ "nl" ] );   // dutch
$.datepicker.formatDate( "dd MM yy", objDate );

如果您不介意扩展Date原型(并且有一些很好的理由不想这样做),您实际上可以提出一个非常简单的方法:

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"

这些函数将应用于所有javascript Date对象。

我是通过DatePipe完成的。

const datePipe = new DatePipe(this.locale);
datePipe.transform(myDate, 'MMM. y');

你可以像这样在构造函数中注入默认区域:

constructor(@Inject(LOCALE_ID) private locale: string){}

Angular的引用https://angular.io/api/common/DatePipe

这是一种不依赖于硬编码数组并支持多个区域设置的方法。

如果你需要一个完整的数组:

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

用法:

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

如果你只需要一个选定的月份(更快):

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

用法:

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

经过测试,在Chrome和IE 11上运行良好。在mozilla上需要做一些修改,因为它返回整个日期。

你可以试试这个:

let d = new Date(), t = d.toDateString()。分割(" "); Console.log (t[2] + " " + t[1] + " " + t[3]);