How to add days to a date in JavaScript
📅May 4, 2022
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 to manage the date object.
- Show/Hide Text Box using JavaScript and jQuery
- How to join two strings in JavaScript
- Remove an element from an array in JavaScript
- Random Password Generator using JavaScript
- Animated sticky header on scroll in JavaScript
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
We can simply develop a prototype for a date for simple access using the same code described previously.
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 all I’ve got for today.
Thank you for reading. Happy Coding..!!