JavaScript Date getMonth()
Syntax & Examples
Date.getMonth() method
The getMonth() method of the Date object in JavaScript returns the month (0 – 11) in the specified date according to local time.
Syntax of Date.getMonth()
The syntax of Date.getMonth() method is:
getMonth()This getMonth() method of Date returns the month (0 – 11) in the specified date according to local time.
Return Type
Date.getMonth() returns value of type Number.
✐ Examples
1 Using getMonth() to get the month of a specific date
In JavaScript, we can use the getMonth() method to get the month from a Date object.
For example,
- We create a new Date object
daterepresenting January 15, 2021. - We use the
getMonth()method to get the month fromdate. - The month is stored in the variable
month. - We log
monthto the console usingconsole.log()method.
JavaScript Program
const date = new Date('2021-01-15');
const month = date.getMonth();
console.log(month);Output
0
2 Using getMonth() with the current date
In JavaScript, we can use the getMonth() method to get the current month from the current date.
For example,
- We create a new Date object
nowrepresenting the current date. - We use the
getMonth()method to get the current month fromnow. - The current month is stored in the variable
currentMonth. - We log
currentMonthto the console usingconsole.log()method.
JavaScript Program
const now = new Date();
const currentMonth = now.getMonth();
console.log(currentMonth);Output
5
3 Using getMonth() with a specific date in the past
In JavaScript, we can use the getMonth() method to get the month from a specific date in the past.
For example,
- We create a new Date object
pastDaterepresenting July 4, 1776. - We use the
getMonth()method to get the month frompastDate. - The month is stored in the variable
pastMonth. - We log
pastMonthto the console usingconsole.log()method.
JavaScript Program
const pastDate = new Date('1776-07-04');
const pastMonth = pastDate.getMonth();
console.log(pastMonth);Output
6
Summary
In this JavaScript tutorial, we learned about getMonth() method of Date: the syntax and few working examples with output and detailed explanation for each example.