Skip to content

Instantly share code, notes, and snippets.

@thegeorgenikhil
Created January 28, 2024 14:46
Show Gist options
  • Save thegeorgenikhil/a73bfc05bf8e4bdaa46c0a3092ea71f4 to your computer and use it in GitHub Desktop.
Save thegeorgenikhil/a73bfc05bf8e4bdaa46c0a3092ea71f4 to your computer and use it in GitHub Desktop.
Returns a string with the time difference between the current time and the time passed as a parameter.
export function timeAgo(value: string) {
const seconds = Math.floor((new Date().getTime() - new Date(value).getTime()) / 1000)
let interval = seconds / 31536000
const rtf = new Intl.RelativeTimeFormat("en", { numeric: 'auto' })
if (interval > 1) { return rtf.format(-Math.floor(interval), 'year') }
interval = seconds / 2592000
if (interval > 1) { return rtf.format(-Math.floor(interval), 'month') }
interval = seconds / 86400
if (interval > 1) { return rtf.format(-Math.floor(interval), 'day') }
interval = seconds / 3600
if (interval > 1) { return rtf.format(-Math.floor(interval), 'hour') }
interval = seconds / 60
if (interval > 1) { return rtf.format(-Math.floor(interval), 'minute') }
return rtf.format(-Math.floor(interval), 'second')
}
// USAGE: timeAgo("2024-01-28 13:04:34.726 +0000 UTC")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment