How to Add Days to Date in JavaScript?
Last Updated :
11 Dec, 2023
In this article, you will learn how to add days to the date in JavaScript. Here, we add days to the current date. There are two methods to add the days to the date object, these are:
Using setDate() Method
The setDate() method is used to set the date of a month into a date object. First, we create a date object (current date), and then add days to the current date and assign to the new date.
Example: This example shows the use of the above-explained approach.
Javascript
function addDays(date, days) {
const newDate = new Date(date);
newDate.setDate(date.getDate() + days);
return newDate;
}
const todayDate = new Date();
const days = 7;
const newDate = addDays(todayDate, days);
console.log( "New Date: " , newDate.toDateString());
|
Output
New Date: Sun Dec 17 2023
Using getTime() Method
The getTime() method returns the number of milliseconds since 1 January 1970. To add the number of days to date, first we convert into milliseconds and then add to the current date (milliseconds).
Example: This example shows the use of the above-explained approach.
Javascript
function addDays(date, days) {
const newDate = new Date(date.getTime()
+ days * 24 * 60 * 60 * 1000);
return newDate;
}
const todayDate = new Date();
const days = 7;
const newDate = addDays(todayDate, days);
console.log( "New Date: " , newDate.toDateString());
|
Output
New Date: Sun Dec 17 2023
Share your thoughts in the comments
Please Login to comment...