1. Date setDate() and getDate() Methods
To add one day to a Date
in JavaScript, call the getDate()
method on the Date
to get the day of the month, then call the setDate()
method on the Date
, passing the sum of the result of getDate()
and 1
as an argument.
For example:
function addOneDay(date) {
date.setDate(date.getDate() + 1);
return date;
}
const date = new Date('2022-05-15T00:00:00.000Z');
const newDate = addOneDay(date);
// 2022-05-16T00:00:00.000Z
console.log(newDate);
Our addOneDay()
function takes a Date
object and the number of days to add as arguments, and returns the same Date
object with the day incremented by one.
The Date
getDate()
method returns a number between 1 and 31 that represents the day of the month of the particular date.
The Date
setDate()
method changes the day of the month of the Date
object to the number passed as an argument.
Note
If the number you specify would change the month or year of the Date
, setDate()
automatically updates the Date
information to reflect this.
// April 25, 2022
const date = new Date('2022-04-25T00:00:00.000Z');
date.setDate(40);
// May 10, 2022
console.log(date); // 2022-05-10T00:00:00.000Z
console.log(date.getDate()); // 10
May has only 30 days, so passing 40
to setDate()
increments the month by one and sets the day of the month to 10
.
Avoiding Side Effects
The setDate()
method mutates the Date
object it is called on. This introduces a side effect into our addOneDay()
function. To avoid modifying the passed Date
and create a pure function, make a copy of the Date
and call setDate()
on this copy, instead of the original.
function addOneDay(date) {
const dateCopy = new Date(date);
dateCopy.setDate(date.getDate() + 1);
return dateCopy;
}
const date = new Date('2022-05-15T00:00:00.000Z');
const newDate = addOneDay(date);
console.log(newDate); // 2022-05-16T00:00:00.000Z
// original not modified
console.log(date); // 2022-05-15T00: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. This makes it a good practice to limit the number of side effects in your programs.
2. date-fns addDays() function
Alternatively, you can use the pure addDays()
function from the date-fns
NPM package to quickly add one day to a Date
. This function takes a Date
object and the number of days to add as arguments, and returns a new Date
object with the newly added days.
import { addDays } from 'date-fns';
const date = new Date('2022-05-15T00:00:00.000Z');
const newDate = addDays(date, 1);
console.log(newDate); // 2022-05-16T00:00:00.000Z
// original not modified
console.log(date); // 2022-05-15T00:00:00.000Z
11 Amazing New JavaScript Features in ES13
This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.