Published on: 12 Oct, 2019

How to get month name from date in Javascript?

Tumblr Digg Google Plus

In this tutorial, we going to learn how to get month name from date in Javascript. There is a built-in function in Javascript called getMonth(). This method will return an integer or a number starting from 0 to 11. Index 0 represents the first month of the year which will be January.

As there are 12 months in a year. We are going to create an array that contains those 12 months. Here is the Javascript of our array.

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

Let's create a function that will accept two parameters and will return the month of the given date. The first parameter will be the date and the second parameter will accept a boolean value which will be true or false. This boolean value will determine if the return month name wants to be shortened or not. If the value is set to true it will return full month name otherwise it will return an abbreviation of the first 3 characters of the month name. Here is the full javascript function code.

<script>
	getMonthName = function(date, fullName){
		var monthName = months[date.getMonth()]
		return fullName ? monthName : monthName.substring(0, 3);
	}
	
	console.log("Current Month is: ", getMonthName(new Date(), true));
</script>

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.