Check interval between two dates

0

I need to check if the interval between two dates does not exceed 12 months, so I did the following in javascript:

var dataFinal = new Date();
var dataInicial = new Date();

dataFinal.setMonth($data.formInput.dataSelecionada.getMonth() +12);
dataInicial.setMonth($data.formInput.dataSelecionada.getMonth() -12);

var situacao = true;
if ($data.formInput.dataSelecionada02 >= dataFinal || $data.formInput.dataSelecionada02 <= dataInicial){
    situacao = false;
} else {
    situacao = true;
}

return (dataInicial+' | '+dataFinal);
But if I select the date 01/01/2017 initially works normally, I get 01/01/2016 and 01/01/2018 but if I change the date to 01/02/2016 instead of the dates they become 01/02/2015 and 01/02/2017 I am returning 01/02/2016 and 01/02/2018 , that is, the day and the month until they change however the year no, how could I solve this?

    
asked by anonymous 07.03.2018 / 17:46

2 answers

0

Hope this helps:

var date1=new Date(2013,5,21);//Remember, months are 0 based in JS
var date2=new Date(2013,9,18);
var year1=date1.getFullYear();
var year2=date2.getFullYear();
var month1=date1.getMonth();
var month2=date2.getMonth();
if(month1===0){ //Have to take into account
  month1++;
  month2++;
}
var numberOfMonths;

1. Not considering the months month1 and month2:

numberOfMonths = (year2 - year1) * 12 + (month2 - month1) - 1;

2.Considering only one of the months:

numberOfMonths = (year2 - year1) * 12 + (month2 - month1);

3. Considering both months:

numberOfMonths = (year2 - year1) * 12 + (month2 - month1) + 1;

Any questions, follow the link to help

    
07.03.2018 / 18:21
0

I believe the error lies in the way you calculate the difference between dates. A simpler approach is as follows:

var date1 = new Date(2018, 01, 01);
var date2 = new Date(2019, 02, 25);

var umDia = 1000*60*60*24;
var diasNoMes = 30;
var meses = Math.round((date2 - date1)/umDia/diasNoMes);

if (meses > 12){
  console.log("Superior a 12 meses!")
}
console.log(meses);

:)

    
07.03.2018 / 18:42