Last active
December 7, 2016 22:58
-
-
Save tmcgann/6e72fc0a726d11a6cfeb67ac487fcd3e to your computer and use it in GitHub Desktop.
Get the time between two dates. MomentJS 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
// Requires momentjs lib | |
function timeBetween(earlier, later) { | |
return humanize(getDiffInMilliseconds(earlier, later)); | |
} | |
function getDiffInMilliseconds(earlier, later) { | |
const DATE_STRING_FORMAT = 'YYYY/MM/DD HH:mm:ss'; | |
const earlierDate = moment(earlier, DATE_STRING_FORMAT); | |
const laterDate = moment(later, DATE_STRING_FORMAT); | |
return laterDate.diff(earlierDate); | |
} | |
function humanize(ms) { | |
const durationFunctionName = getDurationFunctionName(ms); | |
const duration = moment.duration(ms)[durationFunctionName](); | |
const units = durationFunctionName.substr(2).toLowerCase(); | |
return `${Math.floor(duration)} ${units}`; | |
} | |
function getDurationFunctionName(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 'asMinutes'; | |
} | |
if (ms < MS_ONE_DAY) { | |
return 'asHours'; | |
} | |
return 'asDays'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment