JavaScript: Get the name of a month.

This is a guide on how to get the name of a month from a date in JavaScript. In JavaScript, we use the getMonth() method to return the numerical representation of a month. However, this is a zero-based value that starts at 0, where January is 0 and February is 1 and so forth.

As a result, we must manually convert this number if we want to get the textual format of the month.

Custom JavaScript function that converts the number of a month into its name.

Take a look at the following function:

The JavaScript function above takes in the result of the getMonth() method and then converts that number into the name of the month. For example: If you were to pass 0 in as the parameter, this function would return the string “January”.

Let’s take a look at a few examples of how this function can be used.

Getting the name of the current month.

If you want to get the name of the current month, then you can use the function like so:

As you can see, all we had to do here was pass in the result of the getMonth() method. When I ran the code above, the function returned the string “June”.

Get the month name of a specific date.

If you are looking to get the month name from a specific date, then it is pretty much the same as the previous example:

The only difference here is that we passed the date in question into the constructor of our Date object.

Getting the name of next month.

This function will work with any Date object. For example: Let’s say that we wanted to get the name of next month:

Here, we manually worked out what the number of the next month will be before passing the result into our getMonthName function.

Using the toLocaleString method.

You can also use the toLocaleString() method to get the month name from a given date:

This will work fine in most modern browsers.

However, you may run into issues if:

  1. You are trying to get the month names of hundreds or thousands of dates. In situations like this, toLocaleString() can be slow.
  2. You need to provide support for older browsers.

Hopefully, you found this guide useful!

See also: Get the day of the week using JavaScript.

Facebook Comments