How to Add One Day to a Date in JavaScript

Last updated on July 10, 2022
How to Add One Day to a Date in JavaScript

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.

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

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
Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also