How to add days to a date in JavaScript (without a library)

Updated Sep 22, 2023 ⤳ 2 min read

To add a few days to a date in JavaScript, you need to use setDate() on the Date object and increment the current day of the month by one or more days.

🎧 Debugging Jam

Calling all coders in need of a rhythm boost! Tune in to our 24/7 Lofi Coding Radio on YouTube, and let's code to the beat – subscribe for the ultimate coding groove!" Let the bug-hunting begin! 🎵💻🚀

You can do it in three steps:

  1. Get the day of the month via Date.prototype.getDate()
  2. Add one or more days to it
  3. Use Date.prototype.setDate() to update the object

For instance, to add 5 days to a date in JavaScript:


// Get the current date
const currentDate = new Date()
 
// Instantiate another date object to avoid mutating the current date
const futureDate = new Date(currentDate)
futureDate.setDate(futureDate.getDate() + 5)
           
console.log(futureDate)

In the above example, we instantiate the futureDate off the currentDate for two reasons:

  1. To avoid mutating the original date object (currentDate)
  2. To guarantee we add the days to a date object identical to the original

The getDate() method returns the day of the month of our date object. The return value is an integer number between 1 and 31.

Next, we add 5 to the value returned by getDate() - and pass it to setDate() to save the result. 

The Date object works smartly when modifying the days. If the result is outside the acceptable range for the respective month, setDate() will update the Date object accordingly.

For instance, if it's November 28th, and we add 5 days to it, the result would be December 3rd.

Create a helper function to add days to a specific date

To make this functionality reusable, you can create a helper function that accepts a date and an arbitrary number of days to add.


function addDaysToDate(currentDate, daysToAdd) {
    daysToAdd = daysToAdd || 0
    
    // Instantiate a new object based on the current Date
    const futureDate = new Date(currentDate)
    
    // Adding the number of days
    futureDate.setDate(futureDate.getDate() + daysToAdd)
    
    return futureDate
}

So to add 7 days to a date object:


console.log(addDaysToDate(new Date('2022-11-05'), 7))
// expected output: Sat Nov 12 2022 00:00:00 GMT+0000 (Western European Standard Time)

And to add 3 days to today's date:


console.log(addDaysToDate(new Date(), 3))

You can also decrement the days with the same logic. For instance getting yesterday's date.

And that's how you can add days to a date in JavaScript. I hope you found this guide helpful.

Thanks for reading!

Disclaimer: This post may contain affiliate links. I might receive a commission if a purchase is made. However, it doesn’t change the cost you’ll pay.

`
Exit mobile version