从两位数的月份编号中获取月份名称

Get month name from two digit month number

我想从两位数的月份数字(ex- 09)中获取月份名称。我试过这段代码。但它不起作用。该代码仅提供当前月份的名称。正确的代码是什么?

 var formattedMonth = moment().month('09').format('MMMM');

您想在创建 Moment 对象时传递月份:

var formattedMonth = moment('09', 'MM').format('MMMM'); // September

moment(
    '09',           // Desired month
    'MM'            // Tells MomentJs the number is a reference to month
).format('MMMM')    // Formats month as name

您需要将月份作为数字而不是文本传递 - 所以...

var formattedMonth = moment().month(9).format('MMMM');
console.log(formattedMonth)

结果: 十月

虽然 Kevin 的回答没有任何问题,但在不通过 moment 对象的情况下获取月份字符串可能更正确(就效率而言)。

var monthNum = 9;   // assuming Jan = 1
var monthName = moment.months(monthNum - 1);      // "September"
var shortName = moment.monthsShort(monthNum - 1); // "Sep"

对于那些希望这样做并改变语言(语言环境)的人,这就是我所做的

let month = moment().month(09).locale('pt-br').format('MMMM');