JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to increment a date by 1 month in JavaScript?

To increment a date by 1 month, follow the following procedures:

  1. First, get the month for the given Date object by calling the getMonth() method.
  2. Add 1 to the month that you have obtained in step 1 and pass the resulting value to the setMonth() method.

In this way, you can increment a date by 1 month.

let d = new Date();
console.log(d); //Sun Feb 20 2022

d.setMonth(d.getMonth() + 1);
console.log(d); //Sun Mar 20 2022

The getMonth() method is used to get the month of the Date object, and it returns an integer value between 0 and 11. Interestingly, the Date class follows zero-based numbering for the months, which means 0=January, 1=February, 2=March, and so on.

The setMonth() method sets the month for the Date object, and it accepts a zero-based integer value for the month.

If incrementing a date by 1 month pushes it into the next year, then the Date object will automatically update the year accordingly.

let d = new Date('2022-12-25'); //Christmas

d.setMonth(d.getMonth() + 1);
console.log(d.toString()); //Wed Jan 25 2023

In this example, Christmas is represented using the Date object and incrementing it by 1 month gives 25th January 2023.

Recommended Posts