1
I have two dates, for example: 01/01/01 and 01/01/2002. The difference between them is one year. How can I calculate this difference and if it is more than one year make a print.
1
I have two dates, for example: 01/01/01 and 01/01/2002. The difference between them is one year. How can I calculate this difference and if it is more than one year make a print.
1
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, just check if the difference is greater than 365 to see if there is a difference greater than 1 year.
Up until.
1
When messing with dates I recommend using the library Momenjs, because she does all the 'heavy' work involving calculating dates.
With it you can use the function diff()
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>
Browser other questions tagged javascript
You are not signed in. Login or sign up in order to post.