How to calculate and display the sum of dates instantly?

3

Expensive,

I have a situation where I need to create a lease. In the fields, the person who is entering the data has the options:

* months / * start date / * end date

I would like to know how to do this in JavaScript, with instant update. I tested it with this solution , but without success, because I believe it's just integers.

I liked the method onblur , because the result is generated automatically, based on the user's choice.

I need a light!

    
asked by anonymous 28.03.2016 / 22:28

1 answer

2

I recommend using .change on top of the drop with the number of months.

You have the string with the starting date, you can create a Date() with this string ... and from there add the number of months.

Of course, you will also need a date formation, which I would advise:

function formatarData(data) {
    var d = new Date(data),
        mes = '' + (d.getMonth() + 1),
        dia = '' + d.getDate(),
        ano = d.getFullYear();

    if (mes.length < 2) mes = '0' + mes;
    if (dia.length < 2) dia = '0' + dia;

    return [dia, mes, ano].join('/');
}

That is, with your input:

var qtdMeses = 6;
var dtInicio = new Date($("#dataInicio").val());
dtInicio.setMonth(dtInicio.getMonth() + qtdMeses); //adicionando meses

$("#dataTermino").val(formatarData(dtInicio));

EDIT :

dtInicio also has to be formatted before it is used ... I updated its assignment as follows:

var dtInicio = new Date(formatarData($("#dataInicio").val()));

Online sample

OTHER EDIT:

As I said in the comments, I think the best solution is to add N days (since, on January 30 if I add + 1 month, it will return NaN , since there is no February 30th ... So, I prepared another Online Example and made a change in the structure of the events. I created a function to calculate the date ... . This function is called every time the change() event of the number of months dropdown is "triggado" and every time the start date field loses focus ( blur ).

$("#meses").change(function() {
    calcularDataTermino();
});

$("#dataInicio").blur(function() {
    calcularDataTermino();
});

function calcularDataTermino() {
  var qtdMeses = parseInt($("#meses").val());
  var qtdDias = 30 * parseInt($("#meses").val()); // sempre 30 dias + de acordo com a quantidade de meses: 1 mês = +30 dias; 2 meses = + 60 dias; 3 meses = 90 dias;
  var dtInicio = new Date(formatarData($("#dataInicio").val()));


  //dtInicio.setMonth(dtInicio.getMonth() + qtdMeses); //+ N qtdMeses
  dtInicio.setDate(dtInicio.getDate() + qtdDias); //+ N dias

  $("#dataTermino").val(formatarData(dtInicio));
}
    
28.03.2016 / 22:43