-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathunix_timestamp.go
55 lines (49 loc) · 1.49 KB
/
unix_timestamp.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
package rdb
import (
"errors"
"strconv"
"time"
)
// UnixTimestamp is simply a time.Time, but can be used to convert an
// unix timestamp in the database into a native time.Time.
type UnixTimestamp time.Time
// Scan decodes src into an unix timestamp.
func (u *UnixTimestamp) Scan(src interface{}) error {
if u == nil {
return errors.New("rippleapi/common: UnixTimestamp is nil")
}
switch src := src.(type) {
case int64:
*u = UnixTimestamp(time.Unix(src, 0))
case float64:
*u = UnixTimestamp(time.Unix(int64(src), 0))
case string:
return u._string(src)
case []byte:
return u._string(string(src))
case nil:
// Nothing, leave zero value on timestamp
default:
return errors.New("rippleapi/common: unhandleable type")
}
return nil
}
func (u *UnixTimestamp) _string(s string) error {
ts, err := strconv.Atoi(s)
if err != nil {
return err
}
*u = UnixTimestamp(time.Unix(int64(ts), 0))
return nil
}
// MarshalJSON -> time.Time.MarshalJSON
func (u UnixTimestamp) MarshalJSON() ([]byte, error) {
return time.Time(u).MarshalJSON()
}
// UnmarshalJSON -> time.Time.UnmarshalJSON
func (u *UnixTimestamp) UnmarshalJSON(x []byte) error {
t := new(time.Time)
err := t.UnmarshalJSON(x)
*u = UnixTimestamp(*t)
return err
}