How to Add Days to Date in JavaScript

A Date is a built-in object in JavaScript. To create a new Date object, use the new Date(), a set of methods become available to operate on it. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC.

JavaScript does not have any built-in function that can add days to the date. Then, how to add days to the current Date using JavaScript? Well, you can create a function of your own that can add days to the current date.

Add Days to Date in JavaScript

To add days in date in JavaScript, use the combination of date.setDate() and date.getDate() function. These methods are used to set and get the day of the month of the Date object. JavaScript Date objects represent a single moment in time in the platform-independent format.

Date.prototype.addDays = function (days) {
 let date = new Date(this.valueOf());
 date.setDate(date.getDate() + days);
 return date;
}

let date = new Date();

console.log(date.addDays(10));

Output

2021-07-12T10:33:23.550Z

Today’s date is 2nd July 2021. If we add 10 days to the current date, you will get 12th July 2021.

In this example, first, we have created a function that takes days as an argument.

The valueOf() function returns the primitive value of a String object. Then we created a new Date object.

Then we set a date from the current date + 10 days. This takes care of automatically incrementing the month if necessary.

You can write the above function in ES6 fashion, which is a very modern approach.

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

var date = new Date();

console.log(addDays(date, 10));

Output

2021-07-12T10:44:20.301Z

When the new Date() is called a constructor, it returns a new Date object.

That’s it for this tutorial.

Leave a Comment