-1

I am trying to add a certain number of days to currentDate. But the date returned is something weird. The same date if I am trying to subtract with number of days it works fine. Also if I am hardcoding the value instead of taking it from document.getElementById it works fine. P.S : document.getElementById is returning proper value.

var someDateForFuture = new Date();
var numberOfDaysToCalculateForFuture = document.getElementById('futureDateCal').value;
someDateForFuture.setDate(someDateForFuture.getDate() + numberOfDaysToCalculateForFuture); 
alert(someDateForFuture);

Now if I have added 3 to number of days of current date, the alert displays

Sat Apr 01 2017 11:23:57 GMT+0530 (India Standard Time)

Please guide.

nbrooks
  • 18,126
  • 5
  • 54
  • 66
Luxy
  • 77
  • 12

3 Answers3

2

Try this logic should work in this case.

var someDateForFuture= new Date(someDateForFuture.setTime( someDateForFuture.getTime() + numberOfDaysToCalculateForFuture* 86400000 ));
Dark Knight
  • 8,218
  • 4
  • 39
  • 58
2

value is returning a string. First make it into a number, and then add the values:

var future = new Date();
var days = +(document.getElementById('futureDateCal').value);

if (!isNaN(days)) {
    future.setDate(future.getDate() + days); 
}
else {
    alert("Non-numeric input");
}

alert(future);
nbrooks
  • 18,126
  • 5
  • 54
  • 66
1

parseInt() the value you are getting from html

var someDateForFuture = new Date();
var numberOfDaysToCalculateForFuture = parseInt(document.getElementById('futureDateCal').value);
someDateForFuture.setDate(someDateForFuture.getDate() +numberOfDaysToCalculateForFuture); 
 alert(someDateForFuture);
Rishabh
  • 1,205
  • 1
  • 11
  • 20