Add One Day to Date in JavaScript

Add One Day to Date in JavaScript

Learn how to add one day to date in JavaScript using the native date object.

How to Add 1 Day to Date in JavaScript?

The best way to add 1 day to a JavaScript date is by using the Date object. On an existing Date, you can use the getDate function to get the day (between 1 and 31), add 1 to this number, then use setDate to update the date. Here's a short example: date.setDate(date.getDate() + 1).

Using the JavaScript Date Object

In JavaScript, you’ll often manipulate the Date object to do diverse operations (e.g., add days to a date, format a date, etc.).

If you want to add one day to date, you can use a combination of these two Date functions:

  1. yourDate.getDate(): get the day of the month (you'll get a number between 1 and 31)

  2. yourDate.setDate(): update the day of the date to the number passed as a parameter

In practice, let’s say you have this date: 05/12/2022. The getDate() function will return 5. Then you can add one day to this number 5 + 1 = 6. Finally, use setDate() to update the day of the month for your current date object.

Here’s a commented example:

// Create a date
const todayDate = new Date()

// Before adding 1 day
console.log(todayDate.toString())
// Output: "Wed Dec 21 2022 18:19:23 GMT+0100 (Central European Standard Time)"

// Add one day to the current date
todayDate.setDate(todayDate.getDate() + 1)

// After adding 1 day
console.log(todayDate.toString())
// Output: "Thu Dec 22 2022 18:19:23 GMT+0100 (Central European Standard Time)"Bonus: Create a Function to One Day to Date

Now you know how to add days to a date, let’s make your code fancy!

One way to do that is to create a function that takes a date as a parameter, adds one day, and returns it.

Following what we did in the last part, here’s how:

// Create a function to make the logic generic
const addOneDayToDate = (date) => {
  date.setDate(date.getDate() + 1)

  return date
}

// Get the current date
const date = new Date()

// Before adding 1 day
console.log(date.toString())
// Output: "Wed Dec 21 2022 18:24:38 GMT+0100 (Central European Standard Time)"

// Call `addOneDayToDate` with the current date
// and assign the result to a new variable called `tomorrowDate`
const tomorrowDate = addOneDayToDate(date);

// After adding 1 day
console.log(tomorrowDate.toString());
// Output: "Thu Dec 22 2022 18:24:38 GMT+0100 (Central European Standard Time)"

Thanks for reading. Let’s connect!

➡️ I help you grow into Web Development, and I share my journey as a Nomad Software Engineer. Join me on Twitter for more. 🚀🎒