JavaScript Date getMonth() Method



The getMonth() method is a built-in function in JavaScript's Date object. It retrieves the month component of a specified date object, representing the month within the year. The return value will be an integer between 0 to 11 (where 0 indicates the first month of the year and 11 indicates the last month).

If the provided Date object is an invalid date, this method returns Not a Number (NaN) as result.

Syntax

Following is the syntax of JavaScript Date getMonth() method −

getMonth();

This method does not accept any parameters.

Return Value

This method returns an integer representing the month of the specified date object.

Example 1

In the example below, we are using the JavaScript Date getMonth() method to retrieve the month component from the date −

<html>
<body>
<script>
   const currentDate = new Date();
   const currentMonth = currentDate.getMonth();

   document.write(currentMonth);
</script>
</body>
</html>

Output

As we can see the output, the month component has been returned according to the local time.

Example 2

In this example, we are printing the minute value from the specified date value −

<html>
<body>
<script>
   const specificDate = new Date('2023-11-25');
   const monthOfDate = specificDate.getMonth();

   document.write(monthOfDate);
</script>
</body>
</html>

Output

This will return "10" as the month value for the provided date.

Example 3

In here, we are retrieving the current month name through a function −

<html>
<body>
<script>
   function getMonthName(date) {
      const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
      return months[date.getMonth()];
   }

   const currentDate = new Date();
   const currentMonthName = getMonthName(currentDate);
   document.write(currentMonthName);
</script>
</body>
</html>

Output

It returns the name of the month according to the universal time.

Advertisements