Last active
January 23, 2023 16:49
-
-
Save pokedotdev/cf0fcc4db3d35809da36880bdb1d49d4 to your computer and use it in GitHub Desktop.
Get time since a Tweet was created
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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