Javascript Date setMonth(month)

Introduction

Javascript Date setMonth(month) sets the month of the date, which is any number 0 or greater. Numbers greater than 11 add years.

dateObj.setMonth(monthValue[, dayValue])

Parameters

  • monthValue - A zero-based integer representing the month of the year offset from the start of the year. So, 0 represents January, 11 represents December, -1 represents December of the previous year, and 12 represents January of the following year.
  • dayValue - Optional. An integer from 1 to 31, representing the day of the month.

Return value

The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date.

If a parameter is outside of the expected range, setMonth() updates the date accordingly.

For example, if we use 15 for monthValue, the year will be incremented by 1, and 3 will be used for month.

let d = new Date();
console.log(d);//  ww  w . j  a v  a2  s . c o m
d.setMonth(6);
console.log(d);

let endOfMonth = new Date(2016, 7, 31);
console.log(endOfMonth);
endOfMonth.setMonth(1);
console.log(endOfMonth); 

Set the month to 4 (May) and the day to the 20th:

var d = new Date();
d.setMonth(4, 20);//  w  w w. j  ava  2 s  .com
console.log(d);

Set the date to be the last day of last month:

var d = new Date();
d.setMonth(d.getMonth(), 0);//from  w ww  .  ja  v  a  2  s  .  com
console.log(d);



PreviousNext

Related