show difference between start and end date in 1day 2 hours format javascript code example
Example 1: javascript difference between two dates
const date1 = new Date('7/13/2010');
const date2 = new Date('12/15/2010');
console.log(getDifferenceInDays(date1, date2));
console.log(getDifferenceInHours(date1, date2));
console.log(getDifferenceInMinutes(date1, date2));
console.log(getDifferenceInSeconds(date1, date2));
function getDifferenceInDays(date1, date2) {
const diffInMs = Math.abs(date2 - date1);
return diffInMs / (1000 * 60 * 60 * 24);
}
function getDifferenceInHours(date1, date2) {
const diffInMs = Math.abs(date2 - date1);
return diffInMs / (1000 * 60 * 60);
}
function getDifferenceInMinutes(date1, date2) {
const diffInMs = Math.abs(date2 - date1);
return diffInMs / (1000 * 60);
}
function getDifferenceInSeconds(date1, date2) {
const diffInMs = Math.abs(date2 - date1);
return diffInMs / 1000;
}
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');