I have a script that I enter the number of months and returns me the deadline date. But I need to decrease one day of the result

-4

Dev's good afternoon!

I'm trying to create a script that calculates the end date from an initial date and its deadline in months. Ex:

Starting date: 08/01/2018 Deadline: 60 months End Date: 7/31/2023 (60 months - 1 day)

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();
  }
}

Thank you in advance.

    
asked by anonymous 20.08.2018 / 22:55

1 answer

1

After the variable f

add this line f.setDate(f.getDate()-1);

See working example

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);
    //diminui 1 dia da data
    f.setDate(f.getDate()-1);
    document.getElementById("final").value = ("0" + f.getDate()).slice(-2) + "/" + ("0" + (f.getMonth() + 1)).slice(-2) + "/" + f.getFullYear();
  }
}
<input type="text" name="data" id="data" value="01/08/2018"/>
<input type="text" name="meses" id="meses" value="60"/>
<input type="text" name="final" id="final" value=""/>
<button type="button" onclick="calcDate();">Calcular</button>

Another way:

function calcDate() {
  var dat = document.getElementById("data").value;
  var meses = document.getElementById("meses").value;

//Inicialmente formatamos a data para new Date(ano, mes, dia);
partes=dat.split("/");
var myDate=new Date(partes[2],partes[1]-1,partes[0]);
//data final + 60 meses
myDate.setMonth(myDate.getMonth()+parseInt(meses));
//data final - 1 dia
myDate.setDate(myDate.getDate()-1);

var dia=myDate.getDate();
var mes=(myDate.getMonth()+1);

//dia e mes com dois digitos
dia	= (dia.toString().length == 1)?'0'+dia:dia;
mes	= (mes.toString().length == 1)?'0'+mes:mes;

//data final
newDate = dia + "/" + mes + "/" + myDate.getFullYear()

document.getElementById("final").value=newDate;

}
<input type="text" name="data" id="data" value="01/08/2018"/>
<input type="text" name="meses" id="meses" value=""/>
<input type="text" name="final" id="final" value=""/>
<button type="button" onclick="calcDate();">Calcular</button>
    
21.08.2018 / 03:03