The setMonth()
and getMonth()
methods of the Date
object can be used to increment or decrement months from a date in JavaScript.
The following example demonstrates how you can add one month to the current date:
const today = new Date()
const nextMonth = new Date()
// Add 1 Month
nextMonth.setMonth(today.getMonth() + 1)
You can also update the existing JavaScript Date
object as shown below:
const date = new Date()
date.setMonth(date.getMonth() + 1)
To subtract months from a date in JavaScript, simply minus the number of months when updating the date with the setMonth()
method:
const today = new Date()
const lastMonth = new Date()
// Minus 1 Month
lastMonth.setMonth(today.getMonth() - 1)
Note that the
getMonth()
method returns a value between0
and11
representing the month in the given date.0
corresponds to January,1
to February,2
to March, and so on.
Finally, if you are frequently manipulating dates in JavaScript, add a function to Date
’s prototype and call it directly whenever you want to add or subtract months:
Date.prototype.addMonths = function (months) {
const date = new Date(this.valueOf())
date.setMonth(date.getMonth() + months)
return date
}
// Add 1 Month
const nextMonth = new Date(2022, 11, 15)
console.log(nextMonth.addMonths(1))
// Sun Jan 15 2023 00:00:00 GMT+0500 (Pakistan Standard Time)
// Minus 1 Month
const lastMonth = new Date(2022, 11, 15)
console.log(lastMonth.addMonths(-1))
// Tue Nov 15 2022 00:00:00 GMT+0500 (Pakistan Standard Time)