How to add date, from a Date and Number of days typed by the user

Asked

Viewed 1,779 times

3

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

In the console.log I’m capturing the data I need, but at the time the date sum 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 someone help me?

2 answers

2


You could modify the date function to be able to add days to your date, for example:

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

<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");
  });
});
  • I’m sorry, but I couldn’t execute that method...

  • Does it work with onblur? I need to enter a purchase date and onblur calls the method, calculates the date and the method needs to return in the dataValidade field...

  • Does the solution need to use pure javascript? Or can it be in Jquery? I tested this function on the console and it worked

  • Now yes, I just adjusted the variables to my form and it worked right.. Another question, I can calculate the date from a date typed, using the Moment?

  • Yes, the Moment.js library is SUPER complete, you would only need to parse the date typed, and ensure that the user would enter a valid date

  • Cool... I’ll study here then.. helped me a lot.. Thank you

Show 1 more comment

0

Here’s a role 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));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.