-
-
Notifications
You must be signed in to change notification settings - Fork 45
/
utils.go
51 lines (44 loc) · 1.06 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package utils
import (
"fmt"
"time"
)
func Pluralize(num int, thing string) string {
if num == 1 {
return fmt.Sprintf("%d %s", num, thing)
}
return fmt.Sprintf("%d %ss", num, thing)
}
func fmtDuration(amount int, unit string) string {
return fmt.Sprintf("about %s ago", Pluralize(amount, unit))
}
func PrettyTimeAgo(ago time.Duration) string {
if ago < time.Minute {
return "less than a minute ago"
}
if ago < time.Hour {
return fmtDuration(int(ago.Minutes()), "minute")
}
if ago < 24*time.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 fmtDuration(int(ago.Hours()/24/365), "year")
}
func TimeToPrettyTimeAgo(d time.Time) string {
now := time.Now()
ago := now.Sub(d)
return PrettyTimeAgo(ago)
}
func FmtDuration(d time.Duration) string {
d = d.Round(time.Second)
m := d / time.Minute
d -= m * time.Minute
s := d / time.Second
return fmt.Sprintf("%02dm %02ds", m, s)
}