Clue Mediator

Add days to a date in JavaScript

📅February 4, 2021

In this short article, we will show you how to add days to a date in JavaScript. Here, we will add the number of days to the given date using JavaScript.

We can also use the third party library such as moment-js" title="Moment.js">Moment.js to manage the datetime" title="DateTime">date object. You may also check the following articles.

Function

Let’s use the following function to add the number of days to a date using JavaScript.

function addDaysToDate(date, days) {
  var dt = new Date(date);
  dt.setDate(dt.getDate() + days);
  return dt;
}

var currentDate = new Date(); // currentDate.toLocaleDateString() - 2/4/2021
addDaysToDate(currentDate, 2).toLocaleDateString(); // 2/6/2021

var dt1 = new Date('09/02/2021'); // dt1.toLocaleDateString() - 9/2/2021
addDaysToDate(dt1, 5).toLocaleDateString(); // 9/7/2021

Create prototype

With the help of the same function above, we can easily create a prototype for a date for easy access.

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

var currentDate = new Date(); // currentDate.toLocaleDateString() - 2/4/2021
currentDate.addDays(2).toLocaleDateString(); // 2/6/2021

var dt1 = new Date("09/02/2021"); // dt1.toLocaleDateString() - 9/2/2021
dt1.addDays(5).toLocaleDateString(); // 9/7/2021

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂