javascript date difference in days, hours, minutes, seconds code example

Example 1: javascript get hours difference between two dates

// date1 and date2 are date objects

let hours = Math.abs(date1 - date2) / 36e5;

// The subtraction returns the difference between the two dates in milliseconds.
// 36e5 is the scientific notation for 60*60*1000, dividing by which converts
// the milliseconds difference into hours.

Example 2: javascript get remaining time from start and end datetime

function calculateExamRemainingTime(exam_end_at) {

    $(function(){

        const calcNewYear = setInterval(function(){

            const exam_ending_at    = new Date(exam_end_at);
            const current_time      = new Date();
           
            const totalSeconds     = Math.floor((exam_ending_at - (current_time))/1000);;
            const totalMinutes     = Math.floor(totalSeconds/60);
            const totalHours       = Math.floor(totalMinutes/60);
            const totalDays        = Math.floor(totalHours/24);

            const hours   = totalHours - ( totalDays * 24 );
            const minutes = totalMinutes - ( totalDays * 24 * 60 ) - ( hours * 60 );
            const seconds = totalSeconds - ( totalDays * 24 * 60 * 60 ) - ( hours * 60 * 60 ) - ( minutes * 60 );

            const examRemainingHoursSection = document.querySelector('#remainingHours');
            const examRemainingMinutesSection = document.querySelector('#remainingMinutes');
            const examRemainingSecondsSection = document.querySelector('#remainingSeconds');

            examRemainingHoursSection.innerHTML = hours.toString();
            examRemainingMinutesSection.innerHTML = minutes.toString();
            examRemainingSecondsSection.innerHTML = seconds.toString();

        },1000);
    });
}

calculateExamRemainingTime('2025-06-03 20:20:20');