Created
May 11, 2024 14:37
-
-
Save gaievskyi/45b762b81fa3b6fdd9febf4bd1117a1f to your computer and use it in GitHub Desktop.
Relative time ago
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
function timeAgo(time: number, now = Date.now()) { | |
const is = (interval: number, cycle: number) => | |
cycle >= interval ? Math.round(cycle / interval) : 0 | |
const secs = (now - time) / 1000 | |
const mins = is(60, secs) | |
const hours = is(60, mins) | |
const days = is(24, hours) | |
const weeks = is(7, days) | |
const months = is(30, days) | |
const years = is(12, months) | |
let amt = years | |
let cycle = "year" | |
if (secs <= 1) { | |
return "just now" | |
} else if (years > 0) { | |
amt = years | |
cycle = "year" | |
} else if (months > 0) { | |
amt = months | |
cycle = "month" | |
} else if (weeks > 0) { | |
amt = weeks | |
cycle = "week" | |
} else if (days > 0) { | |
amt = days | |
cycle = "day" | |
} else if (hours > 0) { | |
amt = hours | |
cycle = "hour" | |
} else if (mins > 0) { | |
amt = mins | |
cycle = "minute" | |
} else if (secs > 0) { | |
amt = secs | |
cycle = "second" | |
} | |
const v = Math.round(amt) | |
return `${v === 1 ? (amt === hours ? "an" : "a") : v} ${cycle}${v > 1 ? "s" : ""} ago` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment