如何在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"]

其他回答

在IE 11, Chrome, Firefox上测试

const dt = new Date(); Const locale = navigator。语言!= undefined ?导航器。[0]: navigator.language; const fullMonth = dt。toLocaleDateString(区域设置,{month: 'long'}); console.log (fullMonth);

我的最佳解决方案如下:

       var dateValue = Date();
       var month = dateValue.substring(4,7);
       var date = dateValue.substring(8,10);
       var year = dateValue.substring(20,24);
       var finaldateString = date+"-"+month+"-"+year;

您可以使用datejs来实现这一点。检查格式说明符,MMMM给出了月份的名称:

var objDate = new Date("10/11/2009");
document.write(objDate.toString("MMMM"));

datejs本地化了超过150个locale !在这里看到的

这是另一个,支持本地化:)

Date.prototype.getMonthName = function(lang) {
    lang = lang && (lang in Date.locale) ? lang : 'en';
    return Date.locale[lang].month_names[this.getMonth()];
};

Date.prototype.getMonthNameShort = function(lang) {
    lang = lang && (lang in Date.locale) ? lang : 'en';
    return Date.locale[lang].month_names_short[this.getMonth()];
};

Date.locale = {
    en: {
       month_names: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
       month_names_short: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    }
};

然后,您可以轻松地添加对其他语言的支持:

Date.locale.fr = {month_names: [...]};

现在可以使用ECMAScript国际化API来做到这一点:

const date = new date (2009,10,10);/ / 2009-11-10 Const month =日期。toLocaleString('default', {month: 'long'}); console.log(月);

“long”使用月份的全称,“short”使用简短的名称,“narrow”使用更简洁的版本,比如字母语言中的第一个字母。

你可以将浏览器的“默认”更改为任何你喜欢的语言环境(例如:'en-us'),它将为该语言/国家使用正确的名称。

使用toLocaleStringapi,你每次都必须传递locale和选项。如果你要在多个不同的日期使用相同的语言环境信息和格式选项,你可以使用Intl。DateTimeFormat相反:

const formatter = new Intl。DateTimeFormat('fr', {month: 'short'}); Const month1 =格式化程序。格式(新日期()); Const month2 = formatter。format(new Date(2003,5,12)); Console.log (' ${month1}和${month2} ');//当前月份的法语和“juin”。

有关更多信息,请参阅我关于国际化API的博客文章。