Calculate a date from an initial date and a deadline

3

I need to select a start date and a period (in months) for the script to calculate the end date in months.

Detail: Clicking outside the period field already does the whole calculation showing the end date in the corresponding field.

I'm not ready yet because of my lack of JavaScript knowledge.

    
asked by anonymous 08.02.2017 / 11:43

1 answer

2

Maybe it got a little big JS, but already does well what you asked for.

function calcDate() {
  var dat = document.getElementById("data").value;
  var meses = document.getElementById("meses").value;
  if(dat != "" && meses != "") {
    var sp = dat.split("/");
    dat = new Date(sp[2], sp[1]-1, sp[0]);
    var m = meses%12;
    var y = Math.floor(meses/12);
    var tmp = dat.setMonth(dat.getMonth()+m);
    var tmp = dat.setYear(dat.getFullYear()+y);
    var f = new Date(tmp);
    document.getElementById("final").value = ("0" + f.getDate()).slice(-2) + "/" + ("0" + (f.getMonth() + 1)).slice(-2) + "/" + f.getFullYear();
  }
}
<input onblur="calcDate()" id="data" placeholder="dd/mm/yyyy">
<input onblur="calcDate()" id="meses" type="number" placeholder="Prazo em meses">
<input id="final" readonly placeholder="Data Final">
    
08.02.2017 / 12:02