Convert a month number to name in JavaScript
In this tutorial, we are going to learn about how to convert a month number to a name from the JavaScript date object.
To convert a month number to a name, we can use the following function:
This below function takes the month number (like 1 or 2) as an argument and returns the month name in string format.
function getMonthName(month){
const d = new Date();
d.setMonth(month-1);
const monthName = d.toLocaleString("default", {month: "long"});
return monthName;
}
console.log(getMonthName(12)); // "December"
Let’s learn how the above function works:
-
First we initialized a JavaScript
new Date()
constructor. -
We invoked a
setMonth()
method on JavaScriptdate
Object by passing themonth-1
as an argument.
Note: In JavaScript, the month number starts from 0
so we substracted it with -1
to get in JavaScript format.
- The
toLocaleString()
method is used to get the month name in string format
You can also read, how to get a current month name in JavaScript.