Tuesday, February 2, 2021

Add days to a Date using JavaScript

Many times I have face this issue, and hope you too.. this is simple 3 line of code will help and fix this problem.


let days =7 ; // we are going to add 7 days to a date

let cdt = new Date('2021-01-10'); // your date value

let tdt = cdt.setTime(cdt.getTime() + (days * 24 * 60 * 60 * 1000)); // calculation for adding 7 days and adding to time

let targetDT = new Date(tdt).format("yyyy-MM-dd"); // converting back from time to date 

// Output for targetDT will be "2021-01-17"


// With function...

function addDays(theDate, days) {
    return new Date(theDate.getTime() + days*24*60*60*1000);
}

var newDate = addDays(new Date(), 5);


Hope this will help you...

No comments:

Post a Comment

Your feedback is always appreciated. I will try to reply to your queries as soon as time allows.Please don't spam,spam comments will be deleted upon reviews.