Skip to content

Instantly share code, notes, and snippets.

@agm1984
Created November 4, 2018 05:57
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 agm1984/8a2048966378c03495c2fc47f74a4a80 to your computer and use it in GitHub Desktop.
Save agm1984/8a2048966378c03495c2fc47f74a4a80 to your computer and use it in GitHub Desktop.
Shows the amount of time elapsed since a timestamp, with pretty formatting
const showTimeElapsed = (timestamp) => {
if (typeof timestamp !== 'number') return 'NaN'
const SECOND = 1000
const MINUTE = SECOND * 60
const HOUR = MINUTE * 60
const DAY = HOUR * 24
const MONTH = DAY * 30
const YEAR = MONTH * 12
const elapsed = ((new Date()).valueOf() - timestamp)
if (elapsed <= MINUTE) return `${Math.round(elapsed / SECOND)}s`
if (elapsed <= HOUR) return `${Math.round(elapsed / MINUTE)}m`
if (elapsed <= DAY) return `${Math.round(elapsed / HOUR)}h`
if (elapsed <= MONTH) return `${Math.round(elapsed / DAY)}d`
if (elapsed <= YEAR) return `${Math.round(elapsed / MONTH)}mo`
return `${Math.round(elapsed / YEAR)}y`
}
console.log(showTimeElapsed(1541309742360))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment