Add days to a javascript date

Asked

Viewed 806 times

1

Hello I need help in a function that picks the date of a date field with the number of days and displays the new date as per Example:

<label>Data</label>
<input type="date" id="data" value="2018-10-10">
<br>
<label>Dias</label>
<input type="text" id="dias" value="5">
<br>
<label>Data Somada</label>
<input type="text" id="data" value="15/10/2018">
<br>

1 answer

3


<input name="data" type="date" id="data"  />


<input onchange="calculaDataFin();" name="dias" type="number" id="dias" size="70"  />

<input name="datafin" type="date" id="datafin"  readonly/>


<input type="button" onclick="calculaDataFin()">

<script type="text/javascript">

function calculaDataFin() {
var datainicial = document.getElementById("data").value;
var dias = parseInt(document.getElementById("dias").value);
var partes = datainicial.split("-");
var ano = partes[0];
var mes = partes[1]-1;
var dia = partes[2];

datainicial = new Date(ano,mes,dia);
datafinal = new Date(datainicial);
datafinal.setDate(datafinal.getDate() + dias);

var dd = ("0" + datafinal.getDate()).slice(-2);
var mm = ("0" + (datafinal.getMonth()+1)).slice(-2);
var y = datafinal.getFullYear();

var dataformatada = y + '-' + mm + '-' + dd;
document.getElementById('datafin').value = dataformatada;

}

</script>

I found what I need on the Internet! thanks for the help

  • 1

    If you want, an (optimal) alternative is Moment.js: https://momentjs.com/docs/#/manipulating/add/

Browser other questions tagged

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