Javascript - Date setMonth() Method

The setMonth() method sets the month of a date object.

Description

The setMonth() method sets the month of a date object.

January is 0, February is 1, and so on.

This method can also be used to set the day of the month.

Syntax

Date.setMonth(month,day)

Parameter Values

Parameter RequireDescription
month Required. An integer representing the month
day Optional. An integer representing the day of month

For month value, the 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
  • 13 will result in the second month of the next year

For the day value, the expected values are 1-31, but other values are allowed:

  • 0 will result in the last day of the previous month
  • -1 will result in the day before the last day of the previous month
  • If the month has 31 days: 32 will result in the first day of the next month
  • If the month has 30 days: 32 will result in the second day of the next month

Return

A Number, representing the number of milliseconds between the date object and midnight January 1 1970

Set the month to 4 (May):

Demo

//display the date after changing the month.
var d = new Date();
d.setMonth(4);//w w  w.j a v a  2  s .  c o m
console.log(d);

//Set the month to 4 (May) and the day to the 20th:
d.setMonth(4, 20);
console.log(d);


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

d.setMonth(d.getMonth(), 0);
console.log(d);

Result