How to Add Days to Date in JavaScript

To add days in date in JavaScript, you can use the “setDate() and getDate()” methods of the Date object. These methods are used to set and get the day of the month of the Date object.

const date = new Date('2023-04-14'); // Today's date
const daysToAdd = 7; // Number of days to add
date.setDate(date.getDate() + daysToAdd);




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);





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.

Leave a Comment