Skip to content

Instantly share code, notes, and snippets.

@jasonbyrne
Created January 17, 2023 01:36
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 jasonbyrne/46bccea54f40368d9e7ce62f9799ff6c to your computer and use it in GitHub Desktop.
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
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