JavaScript setMonth Function

JavaScript setMonth function is one of the Date Functions, 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 the 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> JS </title>
</head>
<body>
    <h1> Example </h1>
<script>
  var dt = Date();  
  document.write("Date and Time : " + dt + "<br/>");

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

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

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

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> JavaScriptSetMonthFunctions </title>
</head>
<body>
    <h1> JavaScriptsetMonthFunction 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 Example

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

<!DOCTYPE html>
<html>
<head>
    <title> JS </title>
</head>
<body>
    <h1> Example </h1>
<script>
  var dt = Date("2016 10:11:22");
  document.write("DateTime : " + dt + "<br/>");

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

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