1
I need a Javascript code that adds years to the selected date
function calculaData() {
var datainicial = document.getElementById("dataselecionada").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);
//quantidade de dias
datafinal.setDate(datafinal.getDate() + 1);
var dd = ("0" + datafinal.getDate()).slice(-2);
var mm = ("0" + (datafinal.getMonth()+1)).slice(-2);
var y = datafinal.getFullYear();
//var dataformatada = dd + '/' + mm + '/' + y;
var dataformatada = y + '-' + mm + '-' + dd;
document.getElementById('dataAtualizada').value = dataformatada;
}
<label>Data</label>
<input type="date" id="dataselecionada" value="2018-03-10">
<br>
<p>Após adicionar um ano aparce o resultado abaixo no campo date</p>
<label>Data atualizada</label>
<input type="date" id="dataAtualizada">
<p>Exemplo 10/03/2019</p>
<input type="button" onclick="calculaData()" value="Calcular">
summary: pick date return in the field date updated date with the sum of one year. I managed with days but can not add year.
If the date typed is "02/29/16", the result will be "2017-02-29", but 2017 is not leap year, then 02/29 is an invalid date this year. Maybe it’s better to adapt the answers of this question, or use a lib like the Moment js., who already does the math by worrying about all these details. Calculations with dates is more complicated than it seems, and more "simple" approaches (and I would even say "naive") may even "work" for many cases, but there are many exceptions and special cases to consider.
– hkotsubo