Check interval between two dates

Asked

Viewed 359 times

0

I need to check if the interval between two dates does not exceed 12 months, for this 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, me is displayed 01/01/2016 and 01/01/2018 but if I change the date to 01/02/2016 instead of the dates becoming 01/02/2015 and 01/02/2017 is returned to me 01/02/2016 and 01/02/2018, that is, the day and month even change but the year does not, how could solve this?

2 answers

0

I hope this can help:

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 month1 and month2 months:

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 doubt, follows the link to assist

0

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

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

:)

Browser other questions tagged

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