How to add date, from a date and number of days entered by the user

3

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

No console.log I am capturing the data I need, but at the time of the sum of the date it is 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 on the console, it calculates an unexpected date:

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

Can anyone help me?

    
asked by anonymous 20.10.2016 / 05:40

2 answers

2

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

Solution in JQuery
I made this JSFIDDLE using the lib Moment.js 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");
  });
});
    
20.10.2016 / 06:08
0

Here is a function that I use in JAVASCRIPT ...

function somaDias(dt,qtd)
{
    var dt1 = dt.split("/");
    var hj1 = dt1[2]+"-"+dt1[1]+"-"+dt1[0];
    var dtat = new Date(hj1);
    dtat.setDate(dtat.getDate());
    var myDate = new Date(hj1);
    myDate.setDate(myDate.getDate() + (qtd+1));
    var ano = myDate.getFullYear();
    var dia = myDate.getDate(); if(dia<10){dia='0'+dia};
    var mes = (myDate.getMonth()+1); if(mes<10){mes='0'+mes}        
    return (dia+"/"+mes+"/"+ano);
}

// Informe a data e a quantidade de dias que deseja somar.
alert(somaDias('31/03/2017',1));
    
01.04.2017 / 16:37