Adding days to a date in JavaScript

Here’s another quick and easy one while I’m building up blog posts on my new website.

This time we’re adding days to a date. For example, you want to now what the date is 28 days from today.

It’s all very easy but some people reach for complicated ways of mathematically calculating the date, but it’s best done using the JavaScript date object.

// Create a date object with today’s date
const dateToday = new Date()

// Get the date, add 28 days and set the date object
dateToday.setDate(dateToday.getDate() + 28)

// Output: 2022-12-28T00:00:,000Z

The key part above is that we use getDate() to add days.

But what if you want to add hours or weeks to the date instead? Well there are equivalent functions for that.

Adding hours

Here’s how you’d add 12 hours.

dateToday.setHours(dateToday.getHours() + 12)

Adding minutes

Here’s how you’d add 45 minutes.

dateToday.setMinutes(dateToday.getMinutes() + 45)

Adding seconds

Here’s how you’d add 120 seconds.

dateToday.setSeconds(dateToday.getSeconds() + 120)

Adding months

Here’s how you’d add 6 months.

dateToday.setMonth(dateToday.getMonth() + 6)

Adding years

Here’s how you’d add 2 years.

dateToday.setYear(dateToday.getFullYear() + 2)

For more information, see the mdn web docs.

Share