JavaScript date.getMonth() method


The date.getMonth() method in JavaScript returns the month (from 0 to 11) for a specified Date object, according to local time. The months are indexed starting from 0 (January) to 11 (December).

Syntax:

date.getMonth();

Returns:

  • A number between 0 and 11 that represents the month of the specified date.

Example 1: Getting the Month for a Specific Date

const date = new Date('2024-10-22'); // October 22, 2024 const month = date.getMonth(); console.log(month);

Output:

9

Explanation:

  • The Date object represents October 22, 2024. Since months are zero-indexed (0 for January, 1 for February, ..., 9 for October), the getMonth() method returns 9.

Example 2: Getting the Month for the Beginning of the Year

const date = new Date('2024-01-01'); // January 1, 2024 const month = date.getMonth(); console.log(month);

Output:

0

Explanation:

  • For January 1, 2024, getMonth() returns 0, indicating that it is the first month of the year.

Example 3: Getting the Month for a Date in December

const date = new Date('2024-12-31'); // December 31, 2024 const month = date.getMonth(); console.log(month);

Output:

11

Explanation:

  • For December 31, 2024, getMonth() returns 11, representing the twelfth month of the year.

Example 4: Getting the Current Month

const now = new Date(); // Current date and time const currentMonth = now.getMonth(); console.log(currentMonth);

Output:

(Depends on the current month, e.g., if it's October, the output will be 9)

Explanation:

  • This retrieves the current month according to the user's local time. If it's October, for example, the output will be 9.

Summary:

  • date.getMonth() returns the month of the year for a Date object as a zero-based index (0 for January to 11 for December).
  • It is useful for determining the month of a given date in JavaScript.