...
1
16
17 package duration
18
19 import (
20 "fmt"
21 "time"
22 )
23
24
25
26 func ShortHumanDuration(d time.Duration) string {
27
28
29 if seconds := int(d.Seconds()); seconds < -1 {
30 return "<invalid>"
31 } else if seconds < 0 {
32 return "0s"
33 } else if seconds < 60 {
34 return fmt.Sprintf("%ds", seconds)
35 } else if minutes := int(d.Minutes()); minutes < 60 {
36 return fmt.Sprintf("%dm", minutes)
37 } else if hours := int(d.Hours()); hours < 24 {
38 return fmt.Sprintf("%dh", hours)
39 } else if hours < 24*365 {
40 return fmt.Sprintf("%dd", hours/24)
41 }
42 return fmt.Sprintf("%dy", int(d.Hours()/24/365))
43 }
44
45
46
47
48 func HumanDuration(d time.Duration) string {
49
50
51 if seconds := int(d.Seconds()); seconds < -1 {
52 return "<invalid>"
53 } else if seconds < 0 {
54 return "0s"
55 } else if seconds < 60*2 {
56 return fmt.Sprintf("%ds", seconds)
57 }
58 minutes := int(d / time.Minute)
59 if minutes < 10 {
60 s := int(d/time.Second) % 60
61 if s == 0 {
62 return fmt.Sprintf("%dm", minutes)
63 }
64 return fmt.Sprintf("%dm%ds", minutes, s)
65 } else if minutes < 60*3 {
66 return fmt.Sprintf("%dm", minutes)
67 }
68 hours := int(d / time.Hour)
69 if hours < 8 {
70 m := int(d/time.Minute) % 60
71 if m == 0 {
72 return fmt.Sprintf("%dh", hours)
73 }
74 return fmt.Sprintf("%dh%dm", hours, m)
75 } else if hours < 48 {
76 return fmt.Sprintf("%dh", hours)
77 } else if hours < 24*8 {
78 h := hours % 24
79 if h == 0 {
80 return fmt.Sprintf("%dd", hours/24)
81 }
82 return fmt.Sprintf("%dd%dh", hours/24, h)
83 } else if hours < 24*365*2 {
84 return fmt.Sprintf("%dd", hours/24)
85 } else if hours < 24*365*8 {
86 dy := int(hours/24) % 365
87 if dy == 0 {
88 return fmt.Sprintf("%dy", hours/24/365)
89 }
90 return fmt.Sprintf("%dy%dd", hours/24/365, dy)
91 }
92 return fmt.Sprintf("%dy", int(hours/24/365))
93 }
94
View as plain text