Sticking to the date theme, we saw how to get the days between two dates yesterday. Today we are going to learn how we can get a month’s name in JavaScript
.
How to get the month name in Javascript
So let’s start by creating a date object:
const date = new Date();
//Today's date
We can use the JavaScript function toLocaleString
to get a month’s name.
console.log(date.toLocaleString('default', { month: 'long' }));
// May
Instead of the long
option, we can also use the short option and get the month name like, for instance, Dec
.
const december = new Date('12/01/2020');
console.log(december.toLocaleString('default', { month: 'short' }));
// Dec
And as you have seen, we provide the default
keyword. This is the placeholder for the locale
.
So let’s get a months name in a different locale
with this code:
const december = new Date('12/01/2020');
console.log(december.toLocaleString('fr-FR', { month: 'long' }));
// décembre
As you can see, now we get the month’s name from the date object for a different country/language.
See the code examples in this Codepen
I hope you found this a helpful tip, and feel free to check out the Codepen.
See the Pen Vanilla JavaScript get Month Name by Chris Bongers (@rebelchris) on CodePen.
Browser Support
The toLocaleString method is a widely supported method. Feel free to use it.
Thank you for reading, and let’s connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter