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:
Returns:
- A number between 0 and 11 that represents the month of the specified date.
Example 1: Getting the Month for a Specific Date
Output:
Explanation:
- The
Date
object represents October 22, 2024. Since months are zero-indexed (0 for January, 1 for February, ..., 9 for October), thegetMonth()
method returns9
.
Example 2: Getting the Month for the Beginning of the Year
Output:
Explanation:
- For January 1, 2024,
getMonth()
returns0
, indicating that it is the first month of the year.
Example 3: Getting the Month for a Date in December
Output:
Explanation:
- For December 31, 2024,
getMonth()
returns11
, representing the twelfth month of the year.
Example 4: Getting the Current Month
Output:
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 aDate
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.