The best way to get the month name from a date in JavaScript

atapas

Tapas Adhikary

Posted on September 18, 2023

The best way to get the month name from a date in JavaScript

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.

const month = new Date().getMonth();
console.log(month);
Enter fullscreen mode Exit fullscreen mode

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 must avoid a code like this to get a month name from the integer returned by the getMonth() method of the JavaScript Date object.

// 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";
  }
Enter fullscreen mode Exit fullscreen mode

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:

const months = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December",
];
Enter fullscreen mode Exit fullscreen mode

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.

const monthName = months[new Date().getMonth()];
Enter fullscreen mode Exit fullscreen mode

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.

const today = new Date();

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

console.log(month);
Enter fullscreen mode Exit fullscreen mode

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.

const today = new Date();

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

console.log(month);
Enter fullscreen mode Exit fullscreen mode

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.

Liked it? Great. You can explore more about the Date object on the MDN site.

By the way, I have also created a YouTube short on the same topic on my channel, tapaScript. Do you want to check it out?


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.

💖 💪 🙅 🚩
atapas
Tapas Adhikary

Posted on September 18, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related