35

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

enter image description here

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?

Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
  • 9
    I don't get the question... I think it's safe to assume that any year will have the same months :) – Tom Mar 27 '15 at 14:35
  • 1
    Ahhh, Tom beat me to it. I think you're safe to assume the same 12 months every year - It unlikley that we will have a repeat of the 1972 Janemtober indecent where we had to add a whole leap month. – D3vy Mar 27 '15 at 14:37
  • You can pass in a date to moment and format it. Other than that you are going to have to create a function to get it. – Mike Cheel Mar 27 '15 at 14:40
  • @MikeCheel: You are correct sir. As I have done below, and got down-voted for it. Obviously this is not the case :-\ – Mr. Polywhirl Mar 28 '15 at 21:41
  • 3
    I wish they would require a reason for down votes. It doesn't help anyone when there is a downvote without explaining why. – Mike Cheel Mar 28 '15 at 21:43

9 Answers9

93

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.

  • 9
    [Per **Tim R Wood**: "All of these are going away in 2.0.0. `moment.calendar` , `moment.relativeTime` , `moment.months` , ***`moment.monthsShort`*** , `moment.monthsMin` , `moment.weekdays` , `moment.weekdaysShort` , `moment.longDateFormat` , `moment.meridiem` , `moment.ordinal`"](https://github.com/moment/moment/issues/334#issue-5006888) – Mr. Polywhirl Mar 30 '15 at 11:25
  • 7
    You must use localeData() in **2.8**: **moment.localeData().weekdaysShort()** – Kévin Berthommier Nov 05 '16 at 15:30
  • Docs for `localeData`: https://momentjs.com/docs/#/i18n/locale-data/ – johndodo Jun 19 '20 at 07:25
54

Using moment.js you have the following methods:

moment.months() // long names

returns:

[ 'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December' ]

and

moment.monthsShort() // short names

returns:

["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
Mapsy
  • 4,192
  • 1
  • 37
  • 43
Mikel Sanchez
  • 2,870
  • 1
  • 20
  • 28
10

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 < 12; i++) {
 console.log(m.months(i).format('MMMM'));
}
bvaughn
  • 13,300
  • 45
  • 46
  • 1
    Deprecation warning: months accessor is deprecated. Use month instead: var m = moment(); for (var i = 0; i < 12; i++) { console.log(m.month(i).format('MMMM')); } – John Youngtree Jul 13 '16 at 17:01
7

/**
 * Returns an array of all month names for a given language
 * in the specified format.
 *
 * @param lang {string} Language code
 * @param frmt {string} Possible values: {'M','MM','MMM','MMMM'}
 * @return the array of month names
 */
function getMonthNames(lang, frmt) {
  var userLang = moment.lang();            // Save user language
  moment.lang(lang);                       // Switch to specified language
  var months = [];                         // Months array
  var m = moment("2011");                  // Create a moment in 2011
  for (var i = 0; i < 12; i++)             // Loop from 0 to 12 (exclusive)
    months.push(m.months(i).format(frmt)); // Append the formatted month
  moment.lang(userLang);                   // Restore user language
  return months;                           // Return the array of months
}

function println(text) {
  text = arguments.length > 1 ? [].join.call(arguments, ' ') : text;
  document.getElementById('disp').innerHTML += text + '\n';
}

println('English:', getMonthNames('en-US', 'MMM'));
println('Bengali:', getMonthNames('bn', 'MMM'));
println('Español:', getMonthNames('es', 'MMM'));
#disp {
  white-space: pre;
  font-family: monospace;
}
<!-- http://cdnjs.com/libraries/moment.js/ -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.min.js"></script>

<div id="disp"></div>

Output

English: Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
Bengali: জানু,ফেব,মার্চ,এপর,মে,জুন,জুল,অগ,সেপ্ট,অক্টো,নভ,ডিসেম্
Español: ene.,feb.,mar.,abr.,may.,jun.,jul.,ago.,sep.,oct.,nov.,dic.
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • 1
    Funny how I got down voted with no explanation. @RameshRajendran said that he wanted all the month names for a given year. Although the year does not really matter, this function that I have created does the job. – Mr. Polywhirl Mar 28 '15 at 21:39
  • 1
    because some people here just down vote things without analyzing :) #true_story – Richeve Bebedor Dec 20 '15 at 07:26
3

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

var iIndex, 
sArrMonths, sMonth;
for(iIndex = 0; iIndex < 12; iIndex++)
{
    sMonth = moment.localeData().months(moment([0,iIndex]), "");
    sArrMonths.push(sMonth);
}

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

Neha
  • 673
  • 9
  • 16
2

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];
KJ Price
  • 5,774
  • 3
  • 21
  • 34
2

If you want to list month names in a select in React:

  <select
    value={value}
    onChange={handleChange}>

         {moment.months().map(item => (
            <option key={item}>{item}</option>
         ))}

  </select>
msahin
  • 1,520
  • 1
  • 16
  • 22
1

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;
                    }
              )
0

It's 2019 and you shouldn't be using moment.js anymore, since the vanilla Date() class has everything we need. Except for this little bit of functionality.

Here's what I use: There's the months NPM module which has all months in different languages. It's about 991 bytes gzipped.

Example with proper import syntax:

import months from 'months'

console.log(months.de)

Result:

[
  "Januar",
  "Februar",
  "März",
  "April",
  "Mai",
  "Juni",
  "Juli",
  "August",
  "September",
  "Oktober",
  "November",
  "Dezember"
]
RubbelDieKatz
  • 1,134
  • 1
  • 15
  • 32