JavaScript setMonth Function

JavaScript setMonth function is one of the Date Function, which is used to set the Month number and Day Number of a given date as per local time. The syntax of the JavaScript setMonth function is:

 Date.setMonth(Month_Number, Day_Number)

In setMonth function, Day Number is an optional argument. Remember, Month_Number should be between 0 and 11 where 0 is January and 11 in December

JavaScript setMonth Function Example

We are using the setMonth function to set the current month to April.

<!DOCTYPE html>
<html>
<head>
    <title> JavaScript Set Month Functions </title>
</head>
<body>
    <h1> JavaScript setMonth Function Example </h1>
<script>
  var dt = Date();  
  document.write("Date and Time : " + dt + "<br/>");

  dt.setMonth(3);
  document.write("After setMonth() : " + dt);
</script>
</body>
</html>
JavaScript setMonth Function Example

Date and Time: Mon Nov 05 2018 12:00:57 GMT+0530 (Indian Standard Time)
After setMonth(): Thu Apr 05 2018 12:00:57 GMT+0530 (Indian Standard Time)

If you want to set the date to April 1 then use dt.setMonth(3, 1)

JavaScript set Month Example 2

In this example for JavaScript set Month, we set the month number of a custom date to 11 (December)

<!DOCTYPE html>
<html>
<head>
    <title> JavaScript Set Month Functions </title>
</head>
<body>
    <h1> JavaScript setMonth Function Example </h1>
<script>
  var dt = Date("April 1, 2016 10:11:22");
  document.write("Date and Time : " + dt + "<br/>");

  dt.setMonth(11);
  document.write("After setMonth() : " + dt);
</script>
</body>
</html>
JavaScript setMonth Function 2

JavaScript set Month Example 3

In this setMonth example, we set the month number of custom date (without Month or day) to June. This will take the default month January 01 and then sets the value to June.

<!DOCTYPE html>
<html>
<head>
    <title> JavaScript Set Month Functions </title>
</head>
<body>
    <h1> JavaScript setMonth Function Example </h1>
<script>
  var dt = Date("2016 10:11:22");
  document.write("Date and Time : " + dt + "<br/>");

  dt.setMonth(5);
  document.write("After setMonth() : " + dt);
</script>
</body>
</html>
JavaScript setMonth Function Example

Date and Time: Fri Jan 01 2016 10:11:22 GMT+0530 (Indian Standard Time)
After setMonth(): Wed Jun 01 2016 10:11:22 GMT+0530 (Indian Standard Time)