Skip to content

Instantly share code, notes, and snippets.

@andreasvirkus
Created June 21, 2020 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreasvirkus/2a8edfb656134e62f85a3f81bbf29f72 to your computer and use it in GitHub Desktop.
Save andreasvirkus/2a8edfb656134e62f85a3f81bbf29f72 to your computer and use it in GitHub Desktop.
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