I have two dates, for example: 01/01/2001 and 01/01/2002. The difference between them is one year. How can I calculate this difference and if it is more than a year make a print.
I have two dates, for example: 01/01/2001 and 01/01/2002. The difference between them is one year. How can I calculate this difference and if it is more than a year make a print.
Just add this function to your Javascript:
function dataDif(data1, data2){
data1 = data1.split("/");
data2 = data2.split("/");
dif = Math.abs(parseInt(data1[0])-parseInt(data2[0]));
dif += parseInt(Math.abs(parseInt(data1[1])*30.41 - parseInt(data2[1])*30.41));
dif += parseInt(Math.abs(parseInt(data1[2]) - parseInt(data2[2]))*365);
return dif;
}
And use it this way:
dif = dataDif("01/01/2001", "01/01/2002");
if(dif > 365){
//Suas ações
}
This function I did myself. It returns the difference between the two dates in days.
That is, it is only you to check if the difference is greater than 365 to know if there is a difference greater than 1 year.
Until.
When I tinker with dates I advise you to use the Momenjs library because it does all the heavy work of calculating dates.
You can use the diff()
function to calculate the difference between dates.
Example:
var data1 = moment("01-02-2001", "DD-MM-YYYY");
var data2 = moment("01-01-2002", "DD-MM-YYYY");
var diferenca = data2.diff(data1, "years", true);
if (diferenca > 1) {
document.getElementById("saida").innerHTML = "Mais de 1 ano";
} else if (diferenca == 1) {
document.getElementById("saida").innerHTML = "Exatamente 1 ano";
} else {
document.getElementById("saida").innerHTML = "Menos de 1 ano";
}
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<div id="saida"></div>