Files
2026-07-12 02:49:54 +02:00

42 lines
825 B
Go

package formatter
import (
"fmt"
"time"
)
// Relative returns a human-friendly relative time string like "3 hours ago".
func Relative(t time.Time) string {
d := time.Since(t)
if d < time.Minute {
return "just now"
}
if d < time.Hour {
m := int(d.Minutes())
return pluralize(m, "minute") + " ago"
}
if d < 24*time.Hour {
h := int(d.Hours())
return pluralize(h, "hour") + " ago"
}
if d < 30*24*time.Hour {
day := int(d.Hours() / 24)
return pluralize(day, "day") + " ago"
}
if d < 365*24*time.Hour {
month := int(d.Hours() / 24 / 30)
return pluralize(month, "month") + " ago"
}
year := int(d.Hours() / 24 / 365)
return pluralize(year, "year") + " ago"
}
func pluralize(n int, unit string) string {
if n == 1 {
return fmt.Sprintf("1 %s", unit)
}
return fmt.Sprintf("%d %ss", n, unit)
}