Duration Between Two Times

Description: Calculates the number of years, days, hours, minutes and seconds between two date objects. Should handle dates in either order, leap years and daylight savings.
Tested Platform: All Modern Browsers
Language: JavaScript
// 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) {
    var seconds = Math.abs(date2 - date1) / 1000;
    
    var years = parseInt(seconds / (60 * 60 * 24 * 365));
    seconds %= (60 * 60 * 24 * 365); 
    
    var days = parseInt(seconds / (60 * 60 * 24));
    seconds %= (60 * 60 * 24);
    
    var hours = parseInt(seconds / (60 * 60));
    seconds %= (60 * 60);
    
    var mins = parseInt(seconds / 60);
    seconds %= 60;
    
    return { "years": years, "days": days, "hours": hours, "minutes": mins, "seconds": seconds };
}

Submitted: August 20, 2013

Return to the snippets listing