JavaScript Date setMonth()

Posted by

Method

JavaScript Date setMonth() Method

The setMonth() method is used to set the month of a Date object. It is part of the JavaScript Date object, which allows you to work with dates and times.

Syntax

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

dateObj.setMonth(monthValue[, dayValue])

[/dm_code_snippet]

The setMonth() method takes two parameters:

  • monthValue: The numeric value of the month, 0-11, as used in the Date constructor.
  • dayValue: (optional) The numeric value of the day, 1-31.

Examples

The following code will create a Date object and then set the month to November:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let date = new Date();
date.setMonth(10);
console.log(date);

[/dm_code_snippet]

The output will be: Mon Nov 01 2021 00:00:00 GMT+0000 (Coordinated Universal Time)

The following code will create a Date object and then set the month to April and the day to the 15th:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let date = new Date();
date.setMonth(3, 15);
console.log(date);

[/dm_code_snippet]

The output will be: Fri Apr 15 2021 00:00:00 GMT+0000 (Coordinated Universal Time)

Browser Support

The setMonth() method is supported in all major browsers, including Chrome, Firefox, Safari, and Edge.