Get the name of the month from a date in Javascript


Get the name of the month from a date in Javascript

In this post, we will see how to get the name of the month instead of the month's numerical value from a date using JavaScript.

To get the name of a month from a date in JavaScript, we have to use the toLocaleString() method. It returns us the localized name of the month using JavaScript.

This method works in all modern browsers and gives us the localized string representation of the given month.

Example:

const today = new Date()
const month = today.toLocaleString('default', {month:'long'})
console.log(month) //September

If a user wants to pass different dates to get the month name, then we can write a function for it.

Example:

function getMonthName(userDate){
  const date = new Date(userDate)
  const month = date.toLocaleString('default', { month: 'long' })
  return month;
}

console.log(getMonthName('2022-09-04')) //September

Here, we have created a function getMonthName() which takes a date as an argument.

Next, we convert the date string into a valid date object using new Date(userDate).

Every date object has a toLocaleString() method, which returns a date object as a string.

So, we called the toLocaleString() method on the date object and passed month: 'long' as a parameter. It returns the month name in a long format, example 'September'.

We can also get the name of the month in short format, for example, 'Sep' like this:

date.toLocaleString('default', { month: 'short' }) // Sep

If we want a language specific format then we have to change the first parameter, that is the 'default' string in toLocaleString() method like this.

date.toLocaleString('es-MX', { month: 'long' }) // septiembre

Here, we want the month name in Mexican or Spanish language, so we have passed 'es-MX' as the first parameter in the method.


Related Topics:

Check if a timestamp/date is today in JavaScript

Add Days to a Date in JavaScript with Example

Get Tomorrow's Date using JavaScript - Quick Way

Get Current Date in Different Date Formats in JavaScript

Get Yesterday date in JavaScript

[Convert date to long date format using Javascript