Skip to content

Instantly share code, notes, and snippets.

@wlkns
Last active December 8, 2023 11:15
Show Gist options
  • Save wlkns/4e126e79889e1e6f2b6f6a058446ede8 to your computer and use it in GitHub Desktop.
Save wlkns/4e126e79889e1e6f2b6f6a058446ede8 to your computer and use it in GitHub Desktop.
Time Ago.js
const oneDay = 60 * 60 * 24 * 1000
const weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
const getTime = (date: Date) => {
const amPM = date.getHours() > 12 ? 'PM' : 'AM'
const time = [date.getHours() % 12, String(date.getMinutes()).padStart(2, '0')].join(':')
return time + ' ' + amPM
}
const ordinal = (i) => {
const j = i % 10,
k = i % 100
if (j == 1 && k != 11) {
return i + 'st'
}
if (j == 2 && k != 12) {
return i + 'nd'
}
if (j == 3 && k != 13) {
return i + 'rd'
}
return i + 'th'
}
const timeAgo = (date: Date) => {
const currentDate = new Date()
if (date > currentDate) {
throw new Error('errrr')
}
const diffInDays = (currentDate.getTime() - date.getTime()) / oneDay
if (diffInDays < 7) {
const time = getTime(date)
const actualDays = currentDate.getDay() - date.getDay()
const dayOfWeek = date.getDay() % 7
if (actualDays == 0) {
return 'Today, ' + time
} else if (actualDays == 1) {
return 'Yesterday, ' + time
} else {
return weekDays[dayOfWeek] + ', ' + time
}
}
return [months[date.getMonth()], ordinal(date.getDate())].join(' ')
}
export default timeAgo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment