javascript – How to add date from a Date and Number of days entered by the user

Question:

I need to add a date, from a "purchase date" and expiry days.

In console.log I'm capturing the data I need, but at the time of summing the date it's generating an incorrect date.

function addDays(){
   var data = $('#dataCompra').val();
   var dias = $('#tipoproduto').val();
   console.log(dias);
   var result = new Date(data);
   console.log(data);
   console.log(dias);
   result.setDate(result.getDate() + dias);

   console.log(result);
   $('#dataValidade').val(result);

};

</script>

On a date that was to add 5 days, which was the value typed and captured in the console, it calculates an unexpected date:

5
2016-10-10
5
Date 2017-01-03T23:00:00.000Z

Can someone help me?

Answer:

You could modify the date function so that you are able to add days to your date, for example:

Solution in JQuery
I made this JSFIDDLE using the Moment.js lib for a complete time and date solution.

<input type="number" id="num_dias"><button id="gerar">Gerar Data</button>
<input disabled type="date" id="vencimento">

$(function(){
  $("#gerar").on('click', function(){
    var numDays = $("#num_dias").val();
    var venc = moment().add(numDays, 'd').format("DD/MM/YYYY");
    $("#vencimento").val(venc);
    $("#out").html("Adicionado " + numDays + " dias ao total do vencimento");
  });
});
Scroll to Top