support more time units

This commit is contained in:
vilmibm 2020-01-21 14:25:38 -06:00
parent a4b97014d1
commit d7d575fccb
2 changed files with 27 additions and 12 deletions

View file

@ -92,16 +92,26 @@ func Pluralize(num int, thing string) string {
}
}
func fmtDuration(amount int, unit string) string {
return fmt.Sprintf("about %s ago", Pluralize(amount, unit))
}
func FuzzyAgo(ago time.Duration) string {
if ago < time.Minute {
return "less than a minute ago"
}
if ago < time.Hour {
return fmt.Sprintf("about %s ago", Pluralize(int(ago.Minutes()), "minute"))
return fmtDuration(int(ago.Minutes()), "minute")
}
if ago < 24*time.Hour {
return fmt.Sprintf("about %s ago", Pluralize(int(ago.Hours()), "hour"))
return fmtDuration(int(ago.Hours()), "hour")
}
if ago < 30*24*time.Hour {
return fmtDuration(int(ago.Hours())/24, "day")
}
if ago < 365*24*time.Hour {
return fmtDuration(int(ago.Hours())/24/30, "month")
}
return fmt.Sprintf("about %s ago", Pluralize(int(ago.Hours()/24), "day"))
return fmtDuration(int(ago.Hours()/24/365), "year")
}

View file

@ -8,15 +8,20 @@ import (
func TestFuzzyAgo(t *testing.T) {
cases := map[string]string{
"1s": "less than a minute ago",
"30s": "less than a minute ago",
"1m08s": "about 1 minute ago",
"15m0s": "about 15 minutes ago",
"59m10s": "about 59 minutes ago",
"1h10m02s": "about 1 hour ago",
"15h0m01s": "about 15 hours ago",
"30h10m": "about 1 day ago",
"50h": "about 2 days ago",
"1s": "less than a minute ago",
"30s": "less than a minute ago",
"1m08s": "about 1 minute ago",
"15m0s": "about 15 minutes ago",
"59m10s": "about 59 minutes ago",
"1h10m02s": "about 1 hour ago",
"15h0m01s": "about 15 hours ago",
"30h10m": "about 1 day ago",
"50h": "about 2 days ago",
"720h05m": "about 1 month ago",
"3000h10m": "about 4 months ago",
"8760h59m": "about 1 year ago",
"17601h59m": "about 2 years ago",
"262800h19m": "about 30 years ago",
}
for duration, expected := range cases {