CoastalCommitsPastes/client/lib/time-ago.ts

53 lines
1.2 KiB
TypeScript
Raw Permalink Normal View History

// Modified from https://gist.github.com/IbeVanmeenen/4e3e58820c9168806e57530563612886
// which is based on https://stackoverflow.com/questions/3177836/how-to-format-time-since-xxx-e-g-4-minutes-ago-similar-to-stack-exchange-site
const epochs = [
2022-03-23 18:42:22 -04:00
["year", 31536000],
["month", 2592000],
["day", 86400],
["hour", 3600],
["minute", 60],
["second", 1]
2022-03-23 18:34:23 -04:00
] as const
// Get duration
const getDuration = (timeAgoInSeconds: number) => {
2022-03-23 18:42:22 -04:00
for (let [name, seconds] of epochs) {
const interval = Math.floor(timeAgoInSeconds / seconds)
2022-03-23 18:42:22 -04:00
if (interval >= 1) {
return {
interval: interval,
epoch: name
}
}
}
2022-03-23 18:42:22 -04:00
return {
interval: 0,
epoch: "second"
}
2022-03-23 18:34:23 -04:00
}
const timeAgo = (date: Date) => {
2022-03-23 18:42:22 -04:00
const timeAgoInSeconds = Math.floor(
(new Date().getTime() - new Date(date).getTime()) / 1000
)
const { interval, epoch } = getDuration(timeAgoInSeconds)
const suffix = interval === 1 ? "" : "s"
2022-03-23 18:42:22 -04:00
return `${interval} ${epoch}${suffix} ago`
2022-03-23 18:34:23 -04:00
}
const timeUntil = (date: Date) => {
const timeUntilInSeconds = Math.floor(
(new Date(date).getTime() - new Date().getTime()) / 1000
)
const { interval, epoch } = getDuration(timeUntilInSeconds)
const suffix = interval === 1 ? "" : "s"
return `in ${interval} ${epoch}${suffix}`
}
export { timeAgo, timeUntil }