The setMonth method sets the month value of the point in time stored in a Date object. If the already stored day of the month does not exist in the month that you are trying to assign, the remaining days will increase the point in time after the new month is assigned.
Besides, this method can also be used to set the day of the month value, and to increase or decrease the point in time.
The value returned by this method is the quantity of milliseconds passed since January 1st 1970 until the point in time stored in the Date object once it has been modified.
Syntax
The setMonth method has two overloads:
myDate.setMonth( months )
myDate.setMonth( months, days )
myDate.setMonth( months, days )
With:
- months being being a required parameter that consists of an integer number that, when it is between 0 and 11, changes only the month value of the point in time stored in a Date object. Any month value outside that range increases or decreases the point in time of a Date object in a quantity equal to the range's limit being exceeded plus the remaining months. If the parameter is an integer between 0 and 11 but the day of the month in the Date object does not exist for the month being indicated by the parameter, once the new month is assigned the point in time will be increased in a quantity equal to the days remaining in the parameter.
- days being an optional parameter that consists of an integer number that, when it is between 1 and the last day of the month, changes only the day of the month of the point in time stored in a Date object. Any value outside that range increases or decreases the point in time of a Date object in a quantity equal to the range's limit being exceeded plus the remaining days.
- myDate being an object based on the Date object.
Instead of being instantiated from a class, in JavaScript objects are created by replicating other objects. This paradigm is called Prototype-based programming.
Example
The following code uses the setMonth method to set the month of the current date to January:
<script type="text/javascript">
var currentDate = new Date();
var outcome = "The current date is:<br /><br />";
outcome += currentDate;
outcome += "<br /><br />";
currentDate.setMonth(0);
outcome += "After changing the month to January, the resulting date is:";
outcome += "<br /><br />";
outcome += currentDate;
document.write(outcome);
</script>
var currentDate = new Date();
var outcome = "The current date is:<br /><br />";
outcome += currentDate;
outcome += "<br /><br />";
currentDate.setMonth(0);
outcome += "After changing the month to January, the resulting date is:";
outcome += "<br /><br />";
outcome += currentDate;
document.write(outcome);
</script>
Technical Details
The setMonth method belongs to the Date object, it is available since the version 1.0 of JavaScript, and it is supported in all major browsers.
JavaScript Manual >> Date Object >> setMonth Method