Get all months name from year in moment.js

匿名 (未验证) 提交于 2019-12-03 02:06:01

问题:

I want to get all months name from year in moment.js

if the year is 2011, then i want to all months name in momentjs

i have tried this below code, but it's not working for me.

var xxx = moment().months(2011); 

Showing result is

also i have tried xxx.months(), but it's return result is 7

but i want jan,feb,mar,......dec. hmm What can i do?

回答1:

There happens to be a function for that:

moment.monthsShort() // ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] 

Or the same using manual formatting:

Array.apply(0, Array(12)).map(function(_,i){return moment().month(i).format('MMM')}) 

I guess you want to display all names utilizing Moment.js locale data, which is a reasonable approach.



回答2:

Using moment.js you have the following methods:

moment.months() 

returns:

[ 'January',   'February',   'March',   'April',   'May',   'June',   'July',   'August',   'September',   'October',   'November',   'December' ]  moment.monthsShort() 

returns:

["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] 


回答3:

if the year is 2011, then i want to all months name in momentjs

Why does the year matter? Month names don't change.

You could get month names from Moment like so:

var m = moment(); for (var i = 0; i 


回答4:

#disp {   white-space: pre;   font-family: monospace; }
 

Output



回答5:

You can use following function to get a list of Weekdays and Months for listing purpose -

var iIndex,  sArrMonths, sMonth; for(iIndex = 0; iIndex 

You can check live example here - Localized Month and Weekdays List



回答6:

You are going to have to access the months from an array:

var months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];  var monthInt = new Date().getMonth(); var monthString = months[monthInt]; 


回答7:

I needed an array with months number and months name to display them in ng-optiosn, so I extended a little bit Klaster_1's solution.

Array.apply(0, Array(12)).map(                     function(_,i){                           var elem    ={};                           elem.id     = parseInt(i+1);                           elem.name   = moment().month(i).format('MMM');                            return elem;                     }               ) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!