使用Moment.js获取月份名称

Jos*_*ose 18 momentjs

我试图使用Momentjs返回通过月份名称的月号.例如,如果我将"July"传递给moment(),我希望返回7.

通过阅读文档后,我尝试了几种不同的方式,这种方式接近......

console.log(moment().month("July"));
Run Code Online (Sandbox Code Playgroud)

在控制台中,埋在响应中我可以看到这个......

_monthsParse: Array[7]
Run Code Online (Sandbox Code Playgroud)

谁能告诉我如何使用Momentjs正确返回月份数?

kom*_*ten 45

尝试

moment().month("July").format("M");
Run Code Online (Sandbox Code Playgroud)

相关文档:http://momentjs.com/docs/#/get-set/month/

alert(moment().month("July").format("M"));
Run Code Online (Sandbox Code Playgroud)
<script src="https://momentjs.com/downloads/moment.min.js"></script>
Run Code Online (Sandbox Code Playgroud)


San*_*nde 16

任何想要从月份号码获取月份名称的人都可以尝试:

const number = 1; // 0 = Jan & 11 = Dec
moment().month(number).format("MMM"); // Feb
Run Code Online (Sandbox Code Playgroud)

使用以下命令获取完整的月份名称:

const number = 1; // 0 = January & 11 = December
moment().month(number).format("MMMM"); // February
Run Code Online (Sandbox Code Playgroud)

  • 加一.. 有趣的是,这就是我正在寻找的,我只是检查了这个问题以获得一个想法。 (2认同)

小智 6

要使用简单的月份数字,请尝试以下操作:

const month = 2 //Feb
moment(month, 'M').format('MMMM');
Run Code Online (Sandbox Code Playgroud)