✋ Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza
How do you add days to a date in JavaScript?
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.
You can do it in three steps:
- Get the day of the month via
Date.prototype.getDate()
- Add one or more days to it
- 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:
- To avoid mutating the original date object (
currentDate
) - 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!
❤️ You might like:
Top comments (1)
Great article, you got my follow, keep writing!