javascript get difference between two dates in seconds 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 seconds between two dates
var secondBetweenTwoDate = Math.abs((new Date().getTime() - oldDate.getTime()) / 1000);
Example 3: js date difference in seconds
var t1 = new Date();
var t2 = new Date();
var dif = t1.getTime() - t2.getTime();
Example 4: javascript difference between two dates
var date1 = new Date();
var date2 = new Date("2025/07/30 21:59:00");
showDiff(date1,date2);
function showDiff(date1, date2){
var diff = (date2 - date1)/1000;
diff = Math.abs(Math.floor(diff));
var days = Math.floor(diff/(24*60*60));
var leftSec = diff - days * 24*60*60;
var hrs = Math.floor(leftSec/(60*60));
var leftSec = leftSec - hrs * 60*60;
var min = Math.floor(leftSec/(60));
var leftSec = leftSec - min * 60;
console.info("You have " + days + " days " + hrs + " hours " + min + " minutes and " + leftSec + " seconds");
return {
d: days,
h: hrs,
i: min,
s: leftSec
};
}