1. Date
getMonth()
and setMonth()
methods
To add months to a Date
in JavaScript:
- Call the
getMonth()
to get the number of months. - Add the new months.
- Pass the sum to the
setMonth()
method.
For example:
function addMonths(date, months) {
date.setMonth(date.getMonth() + months);
return date;
}
// May 17, 2022
const date = new Date('2022-05-17T00:00:00.000Z');
const newDate = addMonths(date, 4);
// September 17, 2022
console.log(newDate); // 2022-09-17T00:00:00.000Z
Our addMonths()
takes a Date
object and the number of months to add as arguments. It returns the same Date
object with the newly added months.
The Date
getMonth()
returns a zero-based number that represents the month of a particular date.
The Date
setMonth()
method sets the months of a date to a specified zero-based number.
Note: “Zero-based” here means that 0
is January, 1
is February, 2
is March, etc.
If the months added would increase the year of the Date
, setMonth()
will automatically update the information in the Date
object to reflect this.
// November 12, 2022
const date = new Date('2022-11-12T00:00:00.000Z');
date.setMonth(date.getMonth() + 3);
// February 12, 2023
console.log(date); // 2023-02-12T00:00:00.000Z
Here we added 3 months to a date in November 2022. This makes setMonth()
automatically update the year to 2023.
Avoid side effects
The setMonth()
method mutates the Date
object it is called on. This introduces a side effect in our addMonths()
function. To avoid modifying the passed Date
and create a pure function, make a copy of the Date
and call setMonth()
on this copy, instead of the original.
function addMonths(date, months) {
// 👇 Make copy with "Date()" constructor
const dateCopy = new Date(date);
dateCopy.setMonth(dateCopy.getMonth() + months);
return dateCopy;
}
// August 16, 2022
const date = new Date('2022-08-16T00:00:00.000Z');
const newDate = addMonths(date, 3);
// November 16, 2022
console.log(newDate); // 2022-11-16T00:00:00.000Z
// 👇 Original not modified
console.log(date); // 2022-08-16T00:00:00.000Z
Tip: Functions that don’t modify external state (i.e., pure functions) tend to be more predictable and easier to reason about, as they always give the same output for a particular input. This makes it a good practice to limit the number of side effects in your code.
2. date-fns
addMonths()
function
Alternatively, we can use the addMonths()
function from the date-fns
library to quickly add months to a Date
. It works like our pure addMonths()
function.
import { addMonths } from 'date-fns';
// July 14, 2022
const date = new Date('2022-07-14T00:00:00.000Z');
const newDate = addMonths(date, 1);
// August 14, 2022
console.log(newDate); // 2022-08-14T00:00:00.000Z
// Original not modified
console.log(date); // 2022-07-14T00:00:00.000Z
Every Crazy Thing JavaScript Does
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.