Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
export const timeSinceNow = (timestamp) => {
const current = new Date()
const previous = new Date(timestamp * 1000)
const msPerMinute = 60 * 1000
const msPerHour = msPerMinute * 60
const msPerDay = msPerHour * 24
const msPerMonth = msPerDay * 30
const msPerYear = msPerDay * 365
const elapsed = current - previous
if (elapsed < msPerMinute) return Math.round(elapsed / 1000) + ' seconds ago'
if (elapsed < msPerHour) return Math.round(elapsed / msPerMinute) + ' minutes ago'
if (elapsed < msPerDay) return Math.round(elapsed / msPerHour) + ' hours ago'
if (elapsed < msPerMonth) return Math.round(elapsed / msPerDay) + ' days ago'
if (elapsed < msPerYear) return Math.round(elapsed / msPerMonth) + ' months ago'
return Math.round(elapsed / msPerYear) + ' years ago'
}
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.