-
Notifications
You must be signed in to change notification settings - Fork 1
/
time.go
44 lines (35 loc) · 883 Bytes
/
time.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
package xtime
import (
"strconv"
"time"
)
var divs = [...]time.Duration{
time.Duration(1), time.Duration(10), time.Duration(100), time.Duration(1000),
}
func RoundDuration(d time.Duration, digits int) time.Duration {
switch {
case d > time.Second:
d = d.Round(time.Second / divs[digits])
case d > time.Millisecond:
d = d.Round(time.Millisecond / divs[digits])
case d > time.Microsecond:
d = d.Round(time.Microsecond / divs[digits])
}
return d
}
func FormatFixedWidthDuration(d time.Duration) string {
d = RoundDuration(d, 1)
if d < 100*time.Millisecond {
return RoundDuration(d, 0).String()
}
if d < time.Second {
return strconv.FormatFloat(d.Seconds(), 'f', 1, 64) + "s"
}
if d < time.Minute {
if d%time.Second == 0 {
return strconv.FormatInt(int64(d/time.Second), 10) + ".0s"
}
return d.String()
}
return RoundDuration(d, 0).String()
}