Relative time-ago parsing in TypeScript
- Published on
- Published on
- /2 mins read/---
A simple utility function to parse relative time-ago in JavaScript. Showing the time ago in a human-readable format since the given date / time in the past.
function is(interval: number, cycle: number) {
return cycle >= interval ? Math.floor(cycle / interval) : 0
}
export function getTimeAgo(time: string | number | Date, now = Date.now()): string {
if (typeof time === 'string' || time instanceof Date) {
time = new Date(time).getTime()
}
let secs = (now - time) / 1000
let mins = is(60, secs)
let hours = is(60, mins)
let days = is(24, hours)
let weeks = is(7, days)
let months = is(30, days)
let years = is(12, months)
let amt = years
let cycle = 'year'
if (secs <= 1) {
return 'just now'
}
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'
}
let v = Math.floor(amt)
return `${v === 1 ? (amt === hours ? 'an' : 'a') : v} ${cycle}${v > 1 ? 's' : ''} ago`
}
Example usages:
const MARCH_10_2025 = new Date('2025-03-10').getTime()
getTimeAgo(MARCH_10_2025, MARCH_10_2025) // 'just now'
getTimeAgo('2025-03-08', MARCH_10_2025) // '2 days ago'
getTimeAgo('2025-03-02', MARCH_10_2025) // 'a week ago'
Happy time-ago parsing!