setMonth(month)
Sets the month of the date, which is
any number 0 or greater. Numbers greater than 11 add years.
January is 0, February is 1, and so on.
This method can also be used to set the day of the month.
setMonth() |
Yes | Yes | Yes | Yes | Yes |
dateObject.setMonth(month, day);
Parameter | Description |
---|---|
month | Required. An integer representing the month Expected values are 0-11, but other values are allowed: -1 will result in the last month of the previous year 12 will result in the first month of the next year |
day | Optional. An integer representing the day of month
Expected values are 1-31, but other values are allowed: If the month has 31 days, 32 will be the first day of the next month If the month has 30 days, 32 will be the second day of the next month |
return a number representing the number of milliseconds between the date object and midnight January 1 1970.
var myDate = new Date();
myDate.setMonth(2);
console.log(myDate.toString());
The code above generates the following result.
The following code sets date value to May 21st.
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!-- ww w .ja v a2 s. co m-->
var d = new Date();
d.setMonth(4, 21);
document.getElementById("demo").innerHTML = d;
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code set the date to the last day of last month.
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!-- ww w . j a v a 2 s . c om-->
var d = new Date();
d.setMonth(d.getMonth(), 0);
document.getElementById("demo").innerHTML = d;
}
</script>
</body>
</html>
The code above is rendered as follows: