javascript get difference between thwo dates 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 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);
}