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.
// Function to Add days to current date function addDays(date, days) {
const newDate = new Date(date);
newDate.setDate(date.getDate() + days);
return newDate;
} // Get the current date const todayDate = new Date();
// Number of days that we want to // add in current date const days = 7; // Function call to add days const newDate = addDays(todayDate, days); console.log( "New Date: " , newDate.toDateString());
|
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.
// Function to Add days to current date function addDays(date, days) {
const newDate = new Date(date.getTime()
+ days * 24 * 60 * 60 * 1000);
return newDate;
} // Get the current date const todayDate = new Date();
// Number of days that we want to // add in current date const days = 7; // Function call to add days const newDate = addDays(todayDate, days); console.log( "New Date: " , newDate.toDateString());
|
New Date: Sun Dec 17 2023