In order to obtain the previous month from an input date, we can use the
new Date() method to extract the parameters
monthIndex from our defined date object, then subtracting one month from the
getMonth() method to obtain the previous month.
new Date() accepts multiple parameters:
day, optional (default is
An integer value representing the day of the month is used as the third parameter in a number of different examples. This is set to 1 by default, so there is no need to include it.
var d = new Date('2021/07/31'); console.log( new Date(d.getFullYear(), d.getMonth() - 1) );
Tue Jun 01 2021 00:00:00 GMT+0200 (Central European Summer Time)
This will work for the beginning of the year, the beginning of the leap year, and so on. There is no need to extract 30 days or to perform extensive calculations.