Skip to content

Instantly share code, notes, and snippets.

@nicolasparada
Last active June 3, 2018 00:15
Show Gist options
  • Save nicolasparada/ee97395c1887e4d703f5e0760e11cb89 to your computer and use it in GitHub Desktop.
Save nicolasparada/ee97395c1887e4d703f5e0760e11cb89 to your computer and use it in GitHub Desktop.
Formats dates: Just now | 20s | 5m | 10h | 5d | 11 May | 18 Sep, 2017
const MONTHS = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
]
const SECONDS = {
MINUTE: 60,
HOUR: 3600,
DAY: 86400,
MONTH: 2592000,
YEAR: 31536000
}
/**
* @param {Date} date
* @returns {string}
*/
function formatDay(date) {
// @ts-ignore
return String(date.getDate()).padStart(2, '0')
}
/**
* @param {string|Date} x
* @returns {string}
*/
export default function ago(x) {
const date = x instanceof Date ? x : new Date(x)
// @ts-ignore
const secondsAgo = Math.floor((new Date() - date) / 1000)
let interval = Math.floor(secondsAgo / SECONDS.YEAR)
if (interval >= 1) return `${formatDay(date)} ${MONTHS[date.getMonth()]}, ${date.getFullYear()}`
interval = Math.floor(secondsAgo / SECONDS.MONTH)
if (interval >= 1) return `${formatDay(date)} ${MONTHS[date.getMonth()]}`
interval = Math.floor(secondsAgo / SECONDS.DAY)
if (interval == 1) return 'Yesterday'
if (interval > 1) return interval + 'd'
interval = Math.floor(secondsAgo / SECONDS.HOUR)
if (interval >= 1) return interval + 'h'
interval = Math.floor(secondsAgo / SECONDS.MINUTE)
if (interval >= 1) return interval + 'm'
return secondsAgo == 0 ? 'Just now' : secondsAgo + 's'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment