Last active
October 9, 2023 12:11
-
-
Save cahva/58b848900be45779dde7082a362c6de0 to your computer and use it in GitHub Desktop.
Calculate difference between dates in days, hours, mins and secs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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