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

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

当前回答

对我来说,这是最佳解,

对于TypeScript也一样

const env = process.env.REACT_APP_LOCALE || 'en';

const namedMonthsArray = (index?: number): string[] | string => {
  const months = [];

  for (let month = 0; month <= 11; month++) {
    months.push(
      new Date(new Date('1970-01-01').setMonth(month))
        .toLocaleString(env, {
          month: 'long',
        })
        .toString(),
    );
  }
  if (index) {
    return months[index];
  }
  return months;
};

输出是

["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

其他回答

如果您不介意扩展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对象。

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

它可以被用作

var month_Name = new Date().getMonthName();

只是扩展了许多其他优秀的答案-如果你正在使用jQuery -你可以做一些类似的事情

$.fn.getMonthName = function(date) {

    var monthNames = [
    "January", "February", "March",
    "April", "May", "June",
    "July", "August", "September",
    "October", "November", "December"
    ];

    return monthNames[date.getMonth()];

};

其中date等于var d = new date (somevalue)。这样做的主要优点是@nickf避免使用全局名称空间。

不幸的是,提取月份名称的最佳方法是从UTCString表示中提取:

Date.prototype.monthName = function() {
    return this.toUTCString().split(' ')[2]
};

d = new Date();
//=> Thu Mar 06 2014 23:05:21 GMT+0000 (GMT)

d.monthName();
//=> 'Mar'

对我来说,这是最佳解,

对于TypeScript也一样

const env = process.env.REACT_APP_LOCALE || 'en';

const namedMonthsArray = (index?: number): string[] | string => {
  const months = [];

  for (let month = 0; month <= 11; month++) {
    months.push(
      new Date(new Date('1970-01-01').setMonth(month))
        .toLocaleString(env, {
          month: 'long',
        })
        .toString(),
    );
  }
  if (index) {
    return months[index];
  }
  return months;
};

输出是

["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]