How To Convert Month Number To Month Name Using Javascript

Convert Month number to Month name using JavaScript

After we studied Javascript’s built-in methods, we discovered how to convert month number to month name using Javascript. Please see the ways we guide below.

Convert month number to month name using Javascript

Use toString() and substr() method

toString() and substr() are two commonly used methods of string handling in Javascript. See how we use it together in the example below.

Example:

const getMonthName = (monthName) => {
	const date = new Date();

	// Set month
	date.setMonth(monthName - 1);

	// Convert the date object to a string
	const convertDate = date.toString();
	return convertDate.substr(4, 3);
};

console.log("getMonthName: ", getMonthName(1));

Output

getMonthName:  Jan

To convert month number to month name using JavaScript, first, we create a function getMonthName with the input parameter as the number of months. And use the setMonth() method to set the month. Note that January is 0, and February is 1; that’s why the parameter of the setMonth() method is monthName – 1. After we have the month we want, we use toString() to convert it to a string and use substr() to get a part of the output string, which is that month’s name.

Jun is the string that stands for January.

Use toLocaleString() method

This method will return a Date object as a string.

Syntax:

Date.toLocaleString(locales, options)

Parameters:

  • locales: Language Format
  • options: Is an object to set the output of the date

Example:

// Create function getMonthName
const getMonthName = (numberMonth) => {
	const date = new Date();

	// Set month
	date.setMonth(numberMonth - 1);
	return date.toLocaleString("en-US", {
		month: "long",
	});
};

console.log("getMonthName: ", getMonthName(1));

Output

getMonthName:  January

We also create a function getMonthName that takes the number of months as a parameter, as shown in the above example, and sets the month to the Date() object. After we had set the desired number of months, we used the built-in method of the Date object toLocaleString() with the first parameter “en-US” (US English) to format the language. The second number is an object to set the output of the Date as { month: “long” }, showing only the month’s full name.

Summary

In this tutorial, we showed you how to convert month number to month name using JavaScript. How do you feel about the above guidelines? If you want to find more tutorials like this, follow us. We regularly update new guides every day.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *