What is getMonth() in JavaScript?

The getMonth() method in JavaScript returns the month for the specified date according to the local time.

Syntax

We declare the getMonth() method as shown below:

Parameters and return value

The getMonth() method does not take any parameters. Instead, it returns the numeric value (0 - 11) corresponding to the month for the specified date. For example, 0 corresponds to January, and 11 corresponds to December.

Examples

The following code shows the use of the getMonth() method in JavaScript.

First, we declare a new Date object with the current date and time. We then use the getMonth() method to get the month of the specified date:

//Date Object
var d = new Date();
//getMonth() Method
var m = d.getMonth();
//Display the year
console.log("Month:", m);

In the example below, we declare the new Date object with a specified date. The getMonth() method returns the corresponding month for this specified date, as shown below:

//Date Object with a specified date
var d = new Date("December 25, 1999 15:15:00");
//getMonth() Method
var m = d.getMonth();
//Display
console.log("Month:", m);
Copyright ©2024 Educative, Inc. All rights reserved