-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.

4
  • How can this be duplicate. I am not asking how to add number of days. I have issue while adding number of days Commented Oct 18, 2016 at 5:58
  • its working in my case Commented Oct 18, 2016 at 6:01
  • jsbin.com/zasolefumi/edit?html,output Commented Oct 18, 2016 at 6:02
  • parseInt() the value you are getting from html. Commented Oct 18, 2016 at 6:02

3 Answers 3

2

Try this logic should work in this case.

var someDateForFuture= new Date(someDateForFuture.setTime( someDateForFuture.getTime() + numberOfDaysToCalculateForFuture* 86400000 ));
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.