05 de maio de 2021 • 2 min de leitura
Diferença entre datas
Dias, horas, minutos e segundos
Vamos ver a diferença entre duas datas utilizando o Javascript! 😉
class DateDiff {
constructor(firstDate, secondDate) {
this.firstDate = firstDate;
this.secondDate = secondDate;
}
oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
oneHour = 60 * 60 * 1000; // minutes*seconds*milliseconds
oneMinute = 60 * 1000; // seconds*milliseconds
oneMillisecond = 1000; // milliseconds
getDiffDays = () => Math.round(Math.abs((this.firstDate - this.secondDate) / this.oneDay));
getDiffHour = () => Math.round(Math.abs((this.firstDate - this.secondDate) / this.oneHour));
getDiffMinute = () => Math.round(Math.abs((this.firstDate - this.secondDate) / this.oneMinute));
getDiffSecond = () => Math.round(Math.abs((this.firstDate - this.secondDate) / this.oneMillisecond));
}
// teste 1
const firstDate = new Date("2021-05-05");
const secondDate = new Date("2021-05-04");
const test1 = new DateDiff(firstDate, secondDate);
console.log(test1.getDiffDays()); // 1
console.log(test1.getDiffHour()); // 24
console.log(test1.getDiffMinute()); // 1440
console.log(test1.getDiffSecond()); // 86400
// teste 2
const firstDate2 = new Date("2021-05-05 21:00:00");
const secondDate2 = new Date("2021-05-05 20:00:00");
const test2 = new DateDiff(firstDate2, secondDate2);
console.log(test2.getDiffDays()); // 0
console.log(test2.getDiffHour()); // 1
console.log(test2.getDiffMinute()); // 60
console.log(test2.getDiffSecond()); // 3600
// teste 3
const firstDate3 = new Date("2021-05-05 21:00:00");
const secondDate3 = new Date("2021-05-05 21:02:00");
const test3 = new DateDiff(firstDate3, secondDate3);
console.log(test3.getDiffDays()); // 0
console.log(test3.getDiffHour()); // 0
console.log(test3.getDiffMinute()); // 2
console.log(test3.getDiffSecond()); // 120
// teste 4
const firstDate4 = new Date("2021-05-05 21:00:00");
const secondDate4 = new Date("2021-05-05 21:00:02");
const test4 = new DateDiff(firstDate4, secondDate4);
console.log(test4.getDiffDays()); // 0
console.log(test4.getDiffHour()); // 0
console.log(test4.getDiffMinute()); // 0
console.log(test4.getDiffSecond()); // 2