Created
January 17, 2023 01:36
-
-
Save jasonbyrne/46bccea54f40368d9e7ce62f9799ff6c to your computer and use it in GitHub Desktop.
Simple ago function to calculate, with a concise string, how old a post is
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
const DAY_SECONDS = 86400; | |
const WEEK_SECONDS = 604800; | |
const YEAR_SECONDS = WEEK_SECONDS * 52; | |
export function timeAgo(date: Date) { | |
const epoch = Math.round(date.getTime() / 1000); | |
const now = Math.round(Date.now() / 1000); | |
const seconds = now - epoch; | |
const minutes = Math.round(seconds / 60); | |
const hours = Math.round(seconds / 3600); | |
const days = Math.round(seconds / DAY_SECONDS); | |
const weeks = Math.round(seconds / WEEK_SECONDS); | |
const years = Math.round(seconds / YEAR_SECONDS); | |
if (seconds < 15) { | |
return 'now'; | |
} else if (seconds < 60) { | |
return `<1m`; | |
} else if (minutes < 60) { | |
return `${minutes}m`; | |
} else if (hours < 24) { | |
return `${hours}h`; | |
} else if (days < 7) { | |
return `${days}d`; | |
} else if (weeks < 52) { | |
return `${weeks}w`; | |
} else { | |
return `${years}y`; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment