Created
December 7, 2016 23:06
-
-
Save tmcgann/ef032f129c797af4142e7415fd31d8ec to your computer and use it in GitHub Desktop.
Get the time between two dates. No external libraries required.
This file contains hidden or 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 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