const date = new Date('2023-04-14'); // Today's date const daysToAdd = 7; // Number of days to add date.setDate(date.getDate() + daysToAdd); console.log(date);
In this code, a new Date object is created with today’s date.
The number of days to add is stored in the daysToAdd variable.
The setDate() method is then called on the date object by adding daysToAdd to the current date’s day of the month using the getDate() method. This updates the date to 7 days in the future. Finally, the updated date is logged into the console.
The setDate() method modifies the original Date object, so if you need to keep the original date, you should create a new Date object from it, like this:
const originalDate = new Date('2023-04-14'); const daysToAdd = 7; const newDate = new Date(originalDate); newDate.setDate(originalDate.getDate() + daysToAdd); console.log(originalDate); console.log(newDate);
In this code, a new Date object is created from the original date using the new Date(originalDate), and the setDate() method is called on the new date object. The original date object is left unchanged.
Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.