Borislav Hadzhiev
Wed Jan 26 2022·2 min read
Photo by Thought Catalog
To convert a month number to a month name:
Date
object with a date in the given month.toLocaleString()
method to get the name of the month for the date.function toMonthName(monthNumber) { const date = new Date(); date.setMonth(monthNumber - 1); return date.toLocaleString('en-US', { month: 'long', }); } console.log(toMonthName(1)); // 👉️ "January" console.log(toMonthName(2)); // 👉️ "February" console.log(toMonthName(3)); // 👉️ "March"
We created a reusable function that takes a month number and returns the name of the month.
The
Date()
returns a Date
object.
The setMonth takes a zero-based value for the month and sets the value for the given date.
0
, February is 1
, March is 2
, etc.This is why we had to subtract 1
from the passed in value for the month.
We used the Date.toLocaleString method to get the name of the month for the date.
The two parameters we passed to the toLocaleString
method are:
locales
- a string with a BCP 47 language tag or an array of such strings.
You can use any of the available locales, e.g. en-US
for the US, es-MX
for Mexico or en-CA
for Canada. If you need more information about this
parameter, check out the
MDN docs.options
- an object where we can adjust the formatting of the date. Read
more about the options
object in the
MDN docs.In the example, we passed en-US
as the locale
. If you want to use the
visitor's default locale, pass an empty array for the parameter.
function toMonthName(monthNumber) { const date = new Date(); date.setMonth(monthNumber - 1); // 👇️ using visitor's default locale return date.toLocaleString([], { month: 'long', }); } console.log(toMonthName(1)); // 👉️ "January" console.log(toMonthName(2)); // 👉️ "February" console.log(toMonthName(3)); // 👉️ "March"
When the visitor's default locale is used, the output will vary depending on the user's preferred language.
You can also use different values for the month
property in the options
object. Here is an example that returns the short name of the month (first 3
letters).
function toMonthName(monthNumber) { const date = new Date(); date.setMonth(monthNumber - 1); return date.toLocaleString('en-US', { month: 'short', }); } console.log(toMonthName(1)); // 👉️ "Jan" console.log(toMonthName(2)); // 👉️ "Feb" console.log(toMonthName(3)); // 👉️ "Mar"
Another possible value for the month
property is narrow
, which only returns
the first letter of the month name, e.g. J
for January
.
narrow
representation may return the same letter for multiple months in some locales, e.g. in english - January, June, July, would all return the letter J
.