JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to convert month number to month name in JavaScript?

If you have a month number and want to get the month name for that number, then go through the following steps:

  1. Call the Date() constructor and do not pass any arguments to it.
  2. After that, call the setMonth() method and pass the month number.
  3. Finally, call the toLocaleString() method and pass 'en-US' as locales parameter value. If you want the full name of the month, then pass month: 'long' as a key-value pair to the options parameter.
    date.toLocaleString('en-US', {
      month: 'long'
    });
    On the other hand, if you want the short name of the month, then pass month: 'short' as a key-value pair.
    date.toLocaleString('en-US', {
      month: 'short'
    });

Suppose you have 1 as a month number and want to get the month name for it, then run the following code:

let date = new Date();
date.setMonth(1 - 1);
const monthLong = date.toLocaleString('en-US', {
  month: 'long'
});
console.log(monthLong); //"January"
const monthShort = date.toLocaleString('en-US', {
  month: 'short'
});
console.log(monthShort); //"Jan"

Similarly, you can get the month name for month number 9.

let date = new Date();
date.setMonth(9 - 1);
const monthLong = date.toLocaleString('en-US', {
  month: 'long'
});
console.log(monthLong); //"September"
const monthShort = date.toLocaleString('en-US', {
  month: 'short'
});
console.log(monthShort); //"Sep"

Here, 1 is subtracted from the month number because the Date class follows zero-based numbering for months.

Recommended Posts