Created
November 4, 2018 05:57
-
-
Save agm1984/8a2048966378c03495c2fc47f74a4a80 to your computer and use it in GitHub Desktop.
Shows the amount of time elapsed since a timestamp, with pretty formatting
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
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