-
Notifications
You must be signed in to change notification settings - Fork 1
/
xtime.go
84 lines (73 loc) · 1.85 KB
/
xtime.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
package xtime
import (
"context"
"database/sql/driver"
"strconv"
"time"
)
// Time be used to MySql timestamp converting.
type Time int64
// Scan scan time.
func (t *Time) Scan(src any) (err error) {
switch sc := src.(type) {
case time.Time:
if sc.IsZero() {
return
}
*t = Time(sc.Unix())
case string:
var i int64
i, err = strconv.ParseInt(sc, 10, 64)
*t = Time(i)
}
return
}
// Value get time value.
func (t Time) Value() (driver.Value, error) {
return time.Unix(int64(t), 0), nil
}
// Time get time.
func (t Time) Time() time.Time {
return time.Unix(int64(t), 0)
}
func (t *Time) FromDB(bs []byte) error {
timeStr := string(bs)
ti, err := time.ParseInLocation("2006-01-02T15:04:05", timeStr[:19], time.Local)
if err != nil {
return err
}
if ti.IsZero() {
return nil
}
*t = Time(ti.Unix())
return nil
}
func (t Time) ToDB() ([]byte, error) {
unix := time.Unix(int64(t), 0)
return []byte(unix.String()), nil
}
// Duration be used json unmarshal string time, like 1s, 500ms.
type Duration time.Duration
// UnmarshalText unmarshal text to duration.
func (d *Duration) UnmarshalText(text []byte) error {
tmp, err := time.ParseDuration(string(text))
if err == nil {
*d = Duration(tmp)
}
return err
}
// UnitTime duration parse to unit, such as "300ms", "1h30m" or "2h10s".
func (d *Duration) UnitTime() string {
return DurationToUnit(time.Duration(*d))
}
// Shrink will decrease the duration by comparing with context's timeout duration and return new timeout\context\CancelFunc.
func (d Duration) Shrink(c context.Context) (Duration, context.Context, context.CancelFunc) {
if deadline, ok := c.Deadline(); ok {
if ctimeout := time.Until(deadline); ctimeout < time.Duration(d) {
// deliver small timeout
return Duration(ctimeout), c, func() {}
}
}
ctx, cancel := context.WithTimeout(c, time.Duration(d))
return d, ctx, cancel
}