Steve Newton
Steve Newton

Reputation: 1078

Javascript Date add days

var date = new Date();
var date2 = new Date();          
daysinadvance = document.getElementById('AdvanceDays').value;
date2.setDate(date.getDate()+daysinadvance);
console.log(date2 + date + daysinadvance);

Fri Jan 28 2022 18:13:43 GMT+0000 (GMT Daylight Time)  
Mon Apr 28 2014 18:13:43 GMT+0100 (GMT Standard Time)
60

If I pass in a directly typed number so + 60, it works fine but using the variable, I get a date in 2022. All I would like is the date2 to be current date + 60 days so I can update my validation.

Any help please?

Upvotes: 0

Views: 439

Answers (1)

Felix Kling
Felix Kling

Reputation: 817128

Convert the value to a number first, e.g. with the unary plus operator:

var daysinadvance = +document.getElementById('AdvanceDays').value;
//                  ^ unary plus

Otherwise daysinadvance will be a string and you are doing string concatenation.

Upvotes: 8

Related Questions