We can use JavaScript to convert a month number to a name easily by making use of an array of month names. To convert a month number to a name, we simply have to create an array of month names, which we will call months. We will then match the given month number to the month name.


var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthNumber = 8;
var monthName = months[monthNumber-1];

We can put this code in a function, so all we need is to enter in the month number and the month name will be returned. We will call the function monthNameFromNumber().

function monthNameFromNumber(num){
  var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  var monthNumber = Number(num);
  var monthName = months[monthNumber-1];
  return monthName;
}

Now let’s see our function in use with a couple of examples.

function monthNameFromNumber(num){
  var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  var monthNumber = Number(num);
  var monthName = months[monthNumber-1];
  return monthName;
}

console.log(monthNameFromNumber(1));
console.log(monthNameFromNumber(05));
console.log(monthNameFromNumber(12));

#Output
January
May
December

Let’s take a look at another way to get the month name from a number.

Get the Current Month Name From a Number

To start, we can get the current month of the year by using the getMonth() method. It will return a number from 0 to 11, with 0 corresponding to January, and 11 to December.

We can convert the month number we get from the getMonth() method into the month as a String. To do this we just need to make an array with all the months as seen below.

function getCurrentMonthName(){
  var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
}

We can then use the getMonth() value to find the correct month in the array.

function getCurrentMonthName(){
  var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  var currDate = new Date();
  var currMonth = currDate.getMonth();
  return months[currMonth];
}

console.log(getCurrentMonthName());

#Output
October

The value returned by our function getCurrentMonthName() in the code above will be whatever month of the year it currently is, which in this case would be October.

Hopefully this article has been useful in showing how to use JavaScript to convert month number to name.

Categorized in:

JavaScript,

Last Update: March 11, 2024