javascript difference between two dates in days, hours and minutes code example
Example 1: showing difference between dates in minutes js
const today = new Date();
const endDate = new Date(startDate.setDate(startDate.getDate() + 7));
const days = parseInt((endDate - today) / (1000 * 60 * 60 * 24));
const hours = parseInt(Math.abs(endDate - today) / (1000 * 60 * 60) % 24);
const minutes = parseInt(Math.abs(endDate.getTime() - today.getTime()) / (1000 * 60) % 60);
const seconds = parseInt(Math.abs(endDate.getTime() - today.getTime()) / (1000) % 60);
Example 2: javascript get hours difference between two dates
let hours = Math.abs(date1 - date2) / 36e5;
Example 3: javascript difference between two dates in days
function dateDifference(date2, date1) {
const _MS_PER_DAY = 1000 * 60 * 60 * 24;
const utc1 = Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate());
const utc2 = Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate());
return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}
Example 4: 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');
Example 5: javascript difference between two dates in days
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
diffDays(new Date('2014-12-19'), new Date('2020-01-01'));