Created
June 21, 2020 17:12
-
-
Save andreasvirkus/2a8edfb656134e62f85a3f81bbf29f72 to your computer and use it in GitHub Desktop.
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
export const timeSinceNow = (timestamp) => { | |
const current = new Date() | |
const previous = new Date(timestamp * 1000) | |
const msPerMinute = 60 * 1000 | |
const msPerHour = msPerMinute * 60 | |
const msPerDay = msPerHour * 24 | |
const msPerMonth = msPerDay * 30 | |
const msPerYear = msPerDay * 365 | |
const elapsed = current - previous | |
if (elapsed < msPerMinute) return Math.round(elapsed / 1000) + ' seconds ago' | |
if (elapsed < msPerHour) return Math.round(elapsed / msPerMinute) + ' minutes ago' | |
if (elapsed < msPerDay) return Math.round(elapsed / msPerHour) + ' hours ago' | |
if (elapsed < msPerMonth) return Math.round(elapsed / msPerDay) + ' days ago' | |
if (elapsed < msPerYear) return Math.round(elapsed / msPerMonth) + ' months ago' | |
return Math.round(elapsed / msPerYear) + ' years ago' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment