Categories
JavaScript Answers

How to Add Days to JavaScript Date?

Spread the love

Adding days to a JavaScript date is an operation that sometimes we have to do.

In this article, we’ll look at how to add days to a JavaScript date object.

The setDate Method

We can use the setDate method to add days to a date easily.

For instance, we can write:

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

const result = addDays(new Date(2021, 1, 1), 2)
console.log(result)

We have the addDays function to add days.

In the function, we pass in the date to the Date constructor.

Then we call setDate with the getDate method to get the day of the month.

And then we add the days to it.

And finally, we return the result , which has the new date with the days added to it.

Therefore, when we call it in the 2nd last line, we get:

'Wed Feb 03 2021 00:00:00 GMT-0800 (Pacific Standard Time)'

as the value of result .

setDate will compute the new date value no matter what number we pass into it.

For instance, if we write:

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

const result = addDays(new Date(2021, 1, 1), 100)
console.log(result)

Then result is 'Wed May 12 2021 00:00:00 GMT-0700 (Pacific Daylight Time)’ , which is still what we expect.

The setTime Method

Likewise, we can also call the setTime to set the timestamp of the date instead of days.

This lets us add a time more precisely.

For instance, we can write:

const date = new Date(2021, 1, 1)
const duration = 2;
date.setTime(date.getTime() + (duration * 24 * 60 * 60 * 1000));

date.getTime returns the timestamp in milliseconds.

Then we add the duration in days, converted to milliseconds by multiplying it by 24 * 60 * 60 * 1000 .

Then we get 'Wed Feb 03 2021 00:00:00 GMT-0800 (Pacific Standard Time)’ as the new value of date .

Conclusion

We can use native JavaScript date methods to add days to a JavaScript date.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *