-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtime.go
45 lines (40 loc) · 875 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
45
package golib
import (
"fmt"
"time"
)
var APITimeFormats = []string{
"2006-01-02T15:04:05-0700",
time.RFC3339,
}
func FormatTime(t time.Time) string {
return t.Format(APITimeFormats[0])
}
func ParseTime(s string) (time.Time, error) {
for _, tf := range APITimeFormats {
t, err := time.Parse(tf, s)
if err == nil {
return t, nil
}
}
return time.Time{}, fmt.Errorf("Unable to ParseTime %q to any known format.", s)
}
func FormatDuration(d time.Duration) string {
if d == 0 {
return ""
}
h := int(d.Hours())
m := int(d.Minutes()) - h*60
s := int(d.Seconds()) - m*60 - h*60*60
ms := int(d.Milliseconds()) - s*1000 - m*60*1000 - h*60*60*1000
switch {
case h > 0:
return fmt.Sprintf("%dh%dm%ds", h, m, s)
case m > 0:
return fmt.Sprintf("%dm%ds", m, s)
case s > 0:
return fmt.Sprintf("%ds", s)
default:
return fmt.Sprintf("%dms", ms)
}
}