Stephen Sun

Software engineer based in Houston, Texas.

I'm a detail-oriented individual who thrives in fast-paced team environments. I have experience across different industries, working with both front end and back end technologies.

How to add days to a date object

Link to code snippet: GitHub

Dates can be a bit tricky in JavaScript.

Oftentimes, we may need to add a given number of days to a date object.

Date objects have getDate() and setDate() methods that can be used to get and set dates.

Let's first create a function named addDays. This function will need to take in two arguments: a date and the number of days to be added to this date.

const addDays = (date, days) => {
  const newDate = new Date(date)
  newDate.setDate(newDate.getDate() + days)
  return newDate
}

If we directly call the setDate() method on our date object, then the date would be mutated. This could potentially cause issues, especially if we're using this date elsewhere.

Instead, we should create a new date instance, perform the operation and return this new date.

Calling getDate() on our new date object gets us the day of the month according to local time. We can then add the number of days to this value.

Last but not least, we will need to call setDate() on our new date object to set the calculated date.

What if we wanted to add three days to today's date? Let's try it out.

const date = new Date()
const newDate = addDays(date, 3)
console.log(newDate) // Thu Jun 17 2021 21:33:05 GMT-0500 (Central Daylight Time)

Creating a new date instance will give use the current date. We can use our addDays() function and pass our date instance and a value of three for the second argument.

Logging this result gives us Thu Jun 17 2021 21:33:05 GMT-0500 (Central Daylight Time).

(It is currently June 14, 2021 as I'm typing this).