1
I’m developing a simple application that calculates the difference between two dates, on the console I can already make the difference between years but I can’t calculate the difference of month.
var botaoCalcular = document.querySelector("#calcular");
botaoCalcular.addEventListener("click", function (event){
event.preventDefault();
var form = document.querySelector("#calculaPeriodo");
let data1 = form.dataInicio.value;
let data2 = form.dataFim.value;
let dataI = data1;
let dataII = data2;
const dataSplit = dataI.split('/');
const dataSplit2 = dataII.split('/')
const day = dataSplit[0]; // 30
const month = dataSplit[1]; // 03
const year = dataSplit[2]; // 2019
const day2 = dataSplit2[0]; // 30
const month2 = dataSplit2[1]; // 03
const year2 = dataSplit2[2]; // 2019
dataI = new Date(year, month - 1, day);
dataII = new Date(year2, month2 - 1, day2);
const diff = Math.abs(dataI.getTime() - dataII.getTime());
const anos = Math.ceil(diff / (1000 * 60 * 60 * 24 * 365));
const mes = Math.ceil(diff / (1000 * 60 * 60 * 24 * 365));
console.log(dataI);
console.log(dataII);
console.log(diff);
console.log(anos);
console.log(mes);
})
Related: Return in hours the difference between two dates in JAVASCRIPT
– Icaro Martins
Related: Difference between dates
– Icaro Martins
Related: Time difference between two dates with Javascript?
– Icaro Martins
It is not in Javascript but can help you (the idea is the same): https://answall.com/q/370215/112052
– hkotsubo