The best way to get the month name from a date in JavaScript
Tags: javascript, beginners, codenewbie, webdev
Published: 2023-09-18 14:04:47

JavaScript `Date` object provides many helpful methods for dealing with date and time. The list is so vast that it is sometimes hard for developers to track which method provides what value. Also, it is a bit tricky to retrieve a few information straightforwardly. Getting a month's name from a date is undoubtedly such an area of confusion.

This short article will teach you how to get the month name from a date in the most straightforward way with a few added advantages. JavaScript `Date` object provides a method called `getMonth()` to return you the information of the month part in a date.

However, it doesn't return a human-readable month name, like January, February, etc., from the English calendar. Instead, it returns an integer number corresponding to a month like `0` for `January`, `1` for `February`, and so on.

So, if you are running the following code in the month of `September`, the value `8` will be printed in the console.

```javascript
const month = new Date().getMonth();
console.log(month);
```

Now, how can this number be converted into a human-readable month name? What's the best way?

## The obvious but the worst way to get a month's name

The most obvious way to solve it is by using a `if-else` or a `switch-case` statements. It works, but it's too much of a condition and code. On any day, we <mark>must avoid</mark> a code like this to get a month name from the integer returned by the `getMonth()` method of the JavaScript `Date` object.

```javascript
// DON'T DO THIS...
switch(num) {
    case 0:
      month="January";
      break;
    case 1:
      month="February";
      break;
    case 2:
      month="March";
      break;
    // ...
    //  Skipping the other ones to keep it short.
    // ...  
    case 9:
      month="October";
      break;
    case 10:
      month="November";
      break;
    case 11:
      month="December";
      break;
    default:
      month="Invalid month";
  }
```

So, do we have a better way? Indeed, we do. But before that, let's see another `not-so-great` way many developers try out.

## Can't We Use an Array of Month Names to Solve it?

Yes, we certainly can. How about creating an array of English month names like this:

```javascript
const months = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December",
];
```

After that, use that array to return a month name based on the index number passed to it. For example, if we execute the code below in the month of `September`, the `new Date().getMonth()` will return `8`, and `months[8]` will be `September`.

```javascript
const monthName = months[new Date().getMonth()];
```

Problem solved? Yes! But there is a catch, my friend.

The month name `September` may not be the same in other languages and locales. For example, in French, it is `septembre`. How do we handle that? Another array with Frech month names? Well, that won't be scalable as many locales and languages are worldwide!

## The Best Approach: Use the `toLocaleString()` method

The `toLocaleString()` of the JavaScript `Date` object returns a string with the `locale-aware` representation of the date. It means you don't have to maintain(even know) the month names of different locales in your code.

The code snippet below will get you the month's full name in your browser's default language/locale. For example, if you are running this code on `en-US` locale in the month of `September`, you will get `September` as the output.

```javascript
const today = new Date();

// Getting full month name (e.g. "September")
const month = today.toLocaleString('default', { month: 'long' });

console.log(month);
```

How about in French, then? Oh! That's easy. Just pass the French locale(`fr-FR`) instead of `default` to get the job done. The output of the following code will be `septembre` if you run it on that month.

```javascript
const today = new Date();

// Getting full month name (e.g. "September")
const month = today.toLocaleString('fr-FR', { month: 'long' });

console.log(month);
```

> Please note: The `toLocaleString` method internally calls the `Intl.DateTimeFormat` API for enabling locale-aware date-time formatting. You can read more about [Intl.DateTimeFormat on the MDN site](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat).

Liked it? Great. You can explore more about the [Date object on the MDN site](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date).

By the way, I have also created a YouTube short on the same topic on my channel, [`tapaScript`](https://www.youtube.com/tapasadhikary?sub_confirmation=1). Do you want to check it out?

{% youtube ShWCJPlVlb4 %} 

---

## **Before We End...**

That's all. Thanks for reading it. I hope it was insightful. If you liked the tutorial, please post likes and share it in your circles.

Let's connect. I share web development, content creation, Open Source, and career tips on these platforms.

* [**tapaScript on YouTube**](https://www.youtube.com/tapasadhikary?sub_confirmation=1)
    
* [**X(eka Twitter)**](https://twitter.com/tapasadhikary)
    
* [**LinkedIn**](https://www.linkedin.com/in/tapasadhikary/)
    
* [**GitHub**](https://github.com/atapas)