JavaScript Date setMonth()
Syntax & Examples
Date.setMonth() method
The setMonth() method sets the month for a specified date according to local time.
Syntax of Date.setMonth()
There are 2 variations for the syntax of Date.setMonth() method. They are:
1.
setMonth(monthValue)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
monthValue | required | An integer between 0 and 11, representing the months January through December. |
This method sets the month for the specified date.
Returns value of type Number
.
2.
setMonth(monthValue, dateValue)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
monthValue | required | An integer between 0 and 11, representing the months January through December. |
dateValue | optional | An integer between 1 and 31, representing the day of the month. |
This method sets the month and day for the specified date.
Returns value of type Number
.
✐ Examples
1 Using setMonth() method with one argument
In JavaScript, we can use the setMonth() method to set the month of a date.
For example,
- Create a new Date object with the current date and time.
- Use the setMonth() method to set the month to March (month value 2).
- Log the updated date to the console using console.log().
JavaScript Program
const date = new Date();
date.setMonth(2);
console.log(date);
Output
Expected output: The date with the month set to March.
2 Using setMonth() method with two arguments
In JavaScript, we can use the setMonth() method to set the month and day of a date.
For example,
- Create a new Date object with the current date and time.
- Use the setMonth() method to set the month to March (month value 2) and the day to 15.
- Log the updated date to the console using console.log().
JavaScript Program
const date = new Date();
date.setMonth(2, 15);
console.log(date);
Output
Expected output: The date with the month set to March and the day set to 15.
Summary
In this JavaScript tutorial, we learned about setMonth() method of Date: the syntax and few working examples with output and detailed explanation for each example.