// Calculate the number of years, days, hours, minutes and seconds between two JavaScript Date objects.
// Returns an object with appropriate property names.
function getDateDuration(date1, date2) {
let seconds = Math.abs(date2 - date1) / 1000;
let years = parseInt(seconds / (60 * 60 * 24 * 365));
seconds %= (60 * 60 * 24 * 365);
let days = parseInt(seconds / (60 * 60 * 24));
seconds %= (60 * 60 * 24);
let hours = parseInt(seconds / (60 * 60));
seconds %= (60 * 60);
let mins = parseInt(seconds / 60);
seconds %= 60;
return { "years": years, "days": days, "hours": hours, "minutes": mins, "seconds": seconds };
}
Posted: March 20, 2023
Return to the snippets listing