Home  »  ArticlesGuidesHow ToProgrammingTechnology   »   How to Display the Current Month by Name in JavaScript

How to Display the Current Month by Name in JavaScript

This is how you can get and display the current month by name using the JavaScript toLocaleDateString method in your web projects.

JavaScript provides a couple of ways to print out the current month by name. We shall show you two ways.

Option 1: Display Current Month by Name From Array

Here we first create an array with all the month names, then we will use the index as a key to finding the month we want.

Create an array with all the month names, and so use your index as a key to finding the current month as shown here.

var monthNames = ["January", "February", "March", "April", "May","June","July", "August", "September", "October", "November","December"];

Next, we can use the JavaScript Date() object to retrieve the current month then use the result as the index of the array as follows.

var d = new Date();
console.log("The current month is " + monthNames[d.getMonth()]);

The code above outputs the current month. The method above is not very portable and is error-prone as it relies heavily on what you put into the array.

Option 2: Using the Built-In toLocaleDateString Method

The JavaScript toLocaleDateString method can be used to show parts of a date in your preferred format. It returns a string with a language-sensitive representation of the date portion of this date.

The new locales and options arguments let applications specify the language whose formatting conventions should be used and allow to customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation-dependent.

var event = new Date();

console.log(event.toLocaleDateString('de-DE', { month: 'long'}));
// expected output: Februar

console.log(event.toLocaleDateString('ar-EG', { month: 'long'}));
// expected output: فبراير

console.log(event.toLocaleDateString('en-US', { month: 'long'}));
// expected output: February

console.log(event.toLocaleDateString(undefined, { month: 'long'}));
// expected output: February (varies according to default locale)

console.log(event.toLocaleDateString(undefined, { month: 'short'}));
// expected output: Feb (varies according to default locale)

To display a specific month based on a different date you can replace the above and use the UTC() method like so:

event = new Date(Date.UTC(2021, 11, 16, 3, 0, 0));

Ref: [ 1 ]

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.