Skip to content

Instantly share code, notes, and snippets.

@tmcgann
Created December 7, 2016 23:06
Show Gist options
  • Save tmcgann/ef032f129c797af4142e7415fd31d8ec to your computer and use it in GitHub Desktop.
Save tmcgann/ef032f129c797af4142e7415fd31d8ec to your computer and use it in GitHub Desktop.
Get the time between two dates. No external libraries required.
function timeBetween(earlier, later) {
return humanize(getDiffInMilliseconds(earlier, later));
}
function getDiffInMilliseconds(earlier, later) {
const earlierDate = new Date(earlier);
const laterDate = new Date(later);
return (laterDate - earlierDate);
}
function humanize(ms) {
const duration = getDuration(ms);
return `${Math.floor(duration.value)} ${duration.units}`;
}
function getDuration(ms) {
const MS_ONE_MINUTE = 60000;
const MS_ONE_HOUR = MS_ONE_MINUTE * 60;
const MS_ONE_DAY = MS_ONE_HOUR * 24;
if (ms < MS_ONE_HOUR) {
return {
value: (ms / MS_ONE_MINUTE),
units: 'minutes',
};
}
if (ms < MS_ONE_DAY) {
return {
value: (ms / MS_ONE_HOUR),
units: 'hours',
};
}
return {
value: (ms / MS_ONE_DAY),
units: 'days',
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment