Skip to content

Instantly share code, notes, and snippets.

@cahva
Last active October 9, 2023 12:11
Show Gist options
  • Save cahva/58b848900be45779dde7082a362c6de0 to your computer and use it in GitHub Desktop.
Save cahva/58b848900be45779dde7082a362c6de0 to your computer and use it in GitHub Desktop.
Calculate difference between dates in days, hours, mins and secs
function getDifference(toD, fromD = new Date(), zeroPad = false) {
let d1 = new Date(fromD); // Current date and time
let d2 = new Date(toD); // Target date and time
// Calculate difference in milliseconds
let diffMs = Math.abs(d2 - d1);
// Convert to respective units
let diffSeconds = Math.floor(diffMs / 1000);
let diffMinutes = Math.floor(diffSeconds / 60);
let diffHours = Math.floor(diffMinutes / 60);
let diffDays = Math.floor(diffHours / 24);
diffHours = diffHours % 24;
diffMinutes = diffMinutes % 60;
diffSeconds = diffSeconds % 60;
return {
days: diffDays,
hours: diffHours,
minutes: diffMinutes,
seconds: diffSeconds,
};
}
let d = getDifference('2023-11-07T10:00:00', new Date());
const zeropaddedDiff = Object.keys(d).reduce((acc, key) => {
acc[key] = zeroPad(d[key]);
return acc;
}, {});
console.log(`${d.days} days, ${d.hours} hours, ${d.minutes} minutes, ${d.seconds} seconds`);
console.log(`${zeropaddedDiff.days} days, ${zeropaddedDiff.hours} hours, ${zeropaddedDiff.minutes} minutes, ${zeropaddedDiff.seconds} seconds`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment