Skip to content

Instantly share code, notes, and snippets.

@AkyunaAkish
Created June 11, 2018 17:25
Show Gist options
  • Save AkyunaAkish/a335015babd21e6699b028668399ede6 to your computer and use it in GitHub Desktop.
Save AkyunaAkish/a335015babd21e6699b028668399ede6 to your computer and use it in GitHub Desktop.
getPrettyTimeDiff, pass start date and end date to get string showing diff in days, hours, minutes, seconds
function getPrettyTimeDiff(startDateTime, endDateTime) {
// get total seconds between the times
let delta = Math.abs(endDateTime - startDateTime) / 1000;
// calculate (and subtract) whole days
let days = Math.floor(delta / 86400);
delta -= days * 86400;
// calculate (and subtract) whole hours
let hours = Math.floor(delta / 3600) % 24;
delta -= hours * 3600;
// calculate (and subtract) whole minutes
let minutes = Math.floor(delta / 60) % 60;
delta -= minutes * 60;
// what's left is seconds
let seconds = delta % 60; // in theory the modulus is not required
const timeDiffArr = [
{ type: 'Days', val: days },
{ type: 'Hours', val: hours },
{ type: 'Minutes', val: minutes },
{ type: 'Seconds', val: seconds },
];
return timeDiffArr.reduce((final, time) => {
if(time.val > 0) {
final += `${time.type}: ${time.val} `;
}
return final;
}, '').trim();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment