DEV Community

Cover image for The best way to get the month name from a date in JavaScript
Tapas Adhikary
Tapas Adhikary

Posted on • Originally published at blog.greenroots.info

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.

Top comments (12)

Collapse
 
cezarytomczyk profile image
Cezary Tomczyk

Another approach could be to use Intl.DateTimeFormat.

Collapse
 
atapas profile image
Tapas Adhikary

The toLocaleString() method internally call the Intl’s dateFormat method.

Here is a small read about it from MDN

β€œ The toLocaleString() method of Date instances returns a string with a language-sensitive representation of this date. In implementations with Intl.DateTimeFormat API support, this method simply calls Intl.DateTimeFormat.”

Hence I guess it already fits the approach you suggested πŸ˜€

Collapse
 
cezarytomczyk profile image
Cezary Tomczyk

@atapas Agreed. I was referring to Intl.DateTimeFormat because it may trigger curiosity in the reader. Intl refers to internationalisation, writing for those that don't know what it is.

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡

Came for this, specially when the title says "THE BEST" πŸ˜…
intl sure is the way to go whenever you want to fully support internationalisation and to cover all edgy cases I can think of.

Collapse
 
cezarytomczyk profile image
Cezary Tomczyk

@joelbonetr

Came for this, specially when the title says "THE BEST"

Oh, everyone can miss anything. Hence, comments are a great way to contribute to great posts. :-)

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡

Sure! My bad, honestly it's hard to me nowadays to differentiate between click bait and a honest miss πŸ˜…

Thread Thread
 
atapas profile image
Tapas Adhikary

Of course! Comments are a great way to discuss and get better clarifications. Great to have this discussion here.

Getting a bit deeper, the toLocaleString(the best approach in this article) still uses the Intl’s date format which is already locale-aware. So, the intention was never to sound it like a clickbait one, but rather provide a solution that is far better than other older alternatives mentioned. I think, adding a few lines about the Intl will be great to avoid the confusion. What say?

Thread Thread
 
cezarytomczyk profile image
Cezary Tomczyk

@atapas
I think, adding a few lines about the Intl will be great to avoid the confusion. What say?

I'd say yes, please. :-)

Thread Thread
 
atapas profile image
Tapas Adhikary

Done!

Thanks.

Thread Thread
 
cezarytomczyk profile image
Cezary Tomczyk

@atapas One small thing. Link "here" makes no sense out of the context (accessibility rule). I'd propose:

Intl.DateTimeFormat API for enabling locale-aware date-time formatting. You can read more about Intl.DateTimeFormat on MDN site.

where Intl.DateTimeFormat on MDN site becomes a link.

More about link purpose.

Thread Thread
 
atapas profile image
Tapas Adhikary

Great suggestion, done 🫑

Collapse
 
rickdelpo1 profile image
Rick Delpo

I like the array of months method. A while back I wrote a use case for using dates in Javascript without the Moment library. In this example we populate a stacked bar chart for each month (with plain vanilla js and css)
click here, then get the fully commented source code from my codepen
dev.to/rickdelpo1/how-to-populate-...

Happy coding !!