-
Notifications
You must be signed in to change notification settings - Fork 223
/
duration.go
88 lines (69 loc) · 1.56 KB
/
duration.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package schema
import (
"fmt"
"strconv"
"strings"
"time"
)
type Duration time.Duration
func (d Duration) MarshalJSON() ([]byte, error) {
ds := formatDuration(time.Duration(d))
return []byte(fmt.Sprintf(`"%s"`, ds)), nil
}
func (d *Duration) UnmarshalJSON(b []byte) error {
str := strings.Trim(string(b), "\"")
u := strings.Split(str, ":")
ds := u[0]
di, err := strconv.ParseInt(ds[:len(ds)-1], 10, 64)
if err != nil {
return err
}
hs := u[1]
hi, err := strconv.ParseInt(hs[:len(hs)-1], 10, 64)
if err != nil {
return err
}
hi += di * 24
u[1] = fmt.Sprintf("%dh", hi)
dur, err := time.ParseDuration(strings.Join(u[1:], ""))
if err != nil {
return err
}
*d = Duration(dur)
return nil
}
func formatDuration(d time.Duration) string {
t := int64(d.Seconds())
day := t / (60 * 60 * 24)
t = t % (60 * 60 * 24)
hour := t / (60 * 60)
t = t % (60 * 60)
min := t / 60
sec := t % 60
ds := fmt.Sprintf("%dd:%dh:%dm:%ds", day, hour, min, sec)
return ds
}
type Time time.Time
func (t Time) MarshalJSON() ([]byte, error) {
f := "2006-01-02 15:04:05 -0700"
s := time.Time(t).Format(f)
return []byte(fmt.Sprintf(`"%s"`, s)), nil
}
func (t *Time) UnmarshalJSON(b []byte) error {
s := string(b)
f := `"2006-01-02 15:04:05 -0700"`
tt, err := time.Parse(f, s)
if err != nil {
return err
}
*t = Time(tt)
return nil
}
func (t Time) Elapsed() Duration {
d := time.Since(time.Time(t))
return Duration(d)
}
func UnixToTime(unixTime string) (time.Time, error) {
unixTimeInt, err := strconv.ParseInt(unixTime, 10, 64)
return time.Unix(unixTimeInt, 0), err
}