Created
April 4, 2018 20:32
-
-
Save droid001/ad0eecb2db7aff2890247c01fe1a75f1 to your computer and use it in GitHub Desktop.
Creates a more user friendly time stamp string.
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 timeDifference(current, previous) { | |
const milliSecondsPerMinute = 60 * 1000 | |
const milliSecondsPerHour = milliSecondsPerMinute * 60 | |
const milliSecondsPerDay = milliSecondsPerHour * 24 | |
const milliSecondsPerMonth = milliSecondsPerDay * 30 | |
const milliSecondsPerYear = milliSecondsPerDay * 365 | |
const elapsed = current - previous | |
if (elapsed < milliSecondsPerMinute / 3) { | |
return 'just now' | |
} | |
if (elapsed < milliSecondsPerMinute) { | |
return 'less than 1 min ago' | |
} | |
else if (elapsed < milliSecondsPerHour) { | |
return Math.round(elapsed/milliSecondsPerMinute) + ' min ago' | |
} | |
else if (elapsed < milliSecondsPerDay ) { | |
return Math.round(elapsed/milliSecondsPerHour ) + ' h ago' | |
} | |
else if (elapsed < milliSecondsPerMonth) { | |
return Math.round(elapsed/milliSecondsPerDay) + ' days ago' | |
} | |
else if (elapsed < milliSecondsPerYear) { | |
return Math.round(elapsed/milliSecondsPerMonth) + ' mo ago' | |
} | |
else { | |
return Math.round(elapsed/milliSecondsPerYear ) + ' years ago' | |
} | |
} | |
export function timeDifferenceForDate(date) { | |
const now = new Date().getTime() | |
const updated = new Date(date).getTime() | |
return timeDifference(now, updated) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment