Add Days to Current Date in JavaScript
To add days to a Date()
object in JavaScript, use the setDate()
function – inside it get the current date using the .getDate()
function then add the number of days to increment using the addition operator (+
).
To demonstrate this, we will first create a basic example of adding five days to a Date()
object then create a function to add any number of days to a date dynamically.
Adding Days to a Date
In the example below, five days are added to a Date()
object using the current time.
var date = new Date();
date.setDate(date.getDate() + 5);
console.log(date)
Sun Jun 13 2021 20:48:12 GMT+0100 (British Summer Time)
Today's Date Plus N Days in JavaScript
A more robust solution that follows the "don't repeat yourself principles" would be to create a function that we can pass any date and days to add and get the resulting Date()
object back.
function addDaystoDate(date, days) {
let result = new Date();
result.setDate(date.getDate() + 5);
return result;
}
var fst_date = new Date();
var add = 5;
var result = addDaystoDate(fst_date, add);
console.log(result);
Sun Jun 13 2021 21:05:00 GMT+0100 (British Summer Time)
date