Calculate a date from an initial date and a deadline

Asked

Viewed 708 times

3

I need that when selecting a start date and a period (in months) the script calculates in months the end date.

Detail: when clicking outside the period field already do all the calculation displaying the final date in the corresponding field.

I don’t have anything ready yet due to my lack of Javascript knowledge.

inserir a descrição da imagem aqui

  • Gustavo, even if you make your knowledge of JS clear, take some time to learn how the community works at http://answall.com/tour

1 answer

2


Maybe I got a little big the JS, but it already does what you asked.

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">

  • I noticed that this working, but the final date is not being generated certain... for example today’s date 08/02/2017 + 12 = 08/02/2018 or 08/02/2017 + 1 = 08/03/2017

  • 1

    I made some change check if it’s now ok?!

  • 1

    now yes this ok, thank you very much !!!

  • in Chrome and firefox the end date is coming out so "an/an/Nan", some solution?

  • I’m on Chrome and I didn’t verify that mistake, I imagine it’s the fault of input="date" let me take a look

  • @Gustavosamuelmarcolin now works?

  • not working, this still generating "an/an/Nan" ...strange

  • 1

    Tell you what, can you hold it till noon? I’ll test it on all the browsers at noon and update it for you!

  • yes, it may be..

Show 4 more comments

Browser other questions tagged

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