Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
const timeago = (ts) => {
const templates = {
prefix: '',
suffix: ' ',
secs: 'just now',
minute: 'a minute ago',
minutes: '%d minutes ago',
hour: 'an hour ago',
hours: '%d hours ago',
day: 'a day ago',
days: '%d days ago',
month: 'a month ago',
months: '%d months ago',
year: 'a year ago',
years: '%d years ago'
}
const template = function (t, n) {
return templates[t] && templates[t].replace(/%d/i, Math.abs(Math.round(n)))
}
const seconds = time() - ts
const minutes = seconds / 60
const hours = minutes / 60
const days = hours / 24
const years = days / 365
return templates.prefix + (
seconds < 25 && template('secs') ||
seconds < 90 && template('minute', 1) ||
minutes < 45 && template('minutes', minutes) ||
minutes < 90 && template('hour', 1) ||
hours < 24 && template('hours', hours) ||
hours < 42 && template('day', 1) ||
days < 30 && template('days', days) ||
days < 45 && template('month', 1) ||
days < 365 && template('months', days / 30) ||
years < 1.5 && template('year', 1) ||
template('years', years)
) + templates.suffix
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.