In JavaScript, when working with dates, there are times when we need to change the month value in a date. To do this, we can use the method Date.setMonth
. This method is one of several methods available for modifying different components of the Date
.
Suppose we have a specific date and we want to change the month of it. For this, we will first create a new instance of the date and then use the setMonth
method to update it to the new month.
One of the key points to keep in mind when using setMonth
is that the month index starts at zero; that is, January corresponds to 0 and December corresponds to 11. If you pass a value outside this range, JavaScript will automatically adjust to the next or previous months accordingly.
For instance, if we set the month to 13, the date will automatically roll over to January of the following year. This feature can greatly assist programmers as it eliminates the need for complex calculations to change dates.
Also, you can use this method to define a new date along with the corresponding day. This operation must be conducted before utilizing the setMonth
method.
Now let’s see how this method works using an example:
<script>
const date = new Date(2023, 0, 15); // 15 January 2023
console.log('Original date: ', date);
date.setMonth(5); // Changing month to June (index 5)
console.log('Date after changing month: ', date);
date.setMonth(11, 1); // Setting month to December (index 11) and day to 1
console.log('Date after setting month and day: ', date);
</script>
In the code above:
const date = new Date(2023, 0, 15);
This creates a Date
for 15 January 2023.
console.log('Original date: ', date);
Outputs the original date to the console.
date.setMonth(5);
Changes the month to June (index 5).
console.log('Date after changing month: ', date);
Outputs the date after changing the month to the console.
date.setMonth(11, 1);
Sets the month and day to December (index 11) and 1.
console.log('Date after setting month and day: ', date);
Outputs the date after setting the month and day to the console.