Skip to content

Instantly share code, notes, and snippets.

@pokedotdev
Last active January 23, 2023 16:49
Show Gist options
  • Save pokedotdev/cf0fcc4db3d35809da36880bdb1d49d4 to your computer and use it in GitHub Desktop.
Save pokedotdev/cf0fcc4db3d35809da36880bdb1d49d4 to your computer and use it in GitHub Desktop.
Get time since a Tweet was created
const MS = {
SECOND: 1000,
MINUTE: 1000 * 60,
HOUR: 1000 * 60 * 60,
DAY: 1000 * 60 * 60 * 24,
} as const
function getTimeSinceTweet(tweetDate: Date): string {
const currentDate = new Date()
const diff = currentDate.getTime() - tweetDate.getTime()
if (diff < MS.MINUTE) return Math.floor(diff / MS.SECOND) + 's'
if (diff < MS.HOUR) return Math.floor(diff / MS.MINUTE) + 'm'
if (diff < MS.DAY) return Math.floor(diff / MS.HOUR) + 'h'
const isCurrentYear = tweetDate.getFullYear() === currentDate.getFullYear()
const options: Intl.DateTimeFormatOptions = {
month: 'short',
day: 'numeric',
year: isCurrentYear ? undefined : 'numeric',
}
return new Intl.DateTimeFormat('en-US', options).format(tweetDate)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment