Javascript 从两位数的月份数字中获取月份名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31274581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:27:55  来源:igfitidea点击:

Get month name from two digit month number

javascriptjquerymomentjs

提问by GRTZ

I want to get month name from two digit month number (ex- 09). I tried with this code. But it doesn't work. The code give current month name only. What are the correct code for it?

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

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

回答by Matt Johnson-Pint

While there's nothing wrong with Kevin's answer, it is probably more correct (in terms of efficiency) to obtain the month string without going through a momentobject.

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

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

回答by Kevin Boucher

You want to pass the month when you create the Moment object:

您想在创建 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

回答by nril

You need to pass the month as a number, not text - so...

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

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

Result: October

结果:十月

回答by Yandiro

For those looking to do it and changing languages (locale), this is what I did

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

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