forked from Chia-Network/go-chia-libs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timestamp.go
31 lines (27 loc) · 782 Bytes
/
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
package types
import (
"bytes"
"fmt"
"strconv"
"time"
)
// Timestamp Helper type to go to/from uint64 timestamps in json but represent as time.Time in go applications
type Timestamp struct {
time.Time
}
// MarshalJSON marshals the time to unix timestamp
func (t Timestamp) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("%d", t.Time.Unix())), nil
}
// UnmarshalJSON unmarshals from uint64
func (t *Timestamp) UnmarshalJSON(data []byte) error {
// Split accounts for unix timestamps in float form (1668050986.646834)
// In these cases, we just parse the seconds and ignore the decimal
splits := bytes.Split(data, []byte(`.`))
intval, err := strconv.Atoi(string(splits[0]))
if err != nil {
return err
}
t.Time = time.Unix(int64(intval), 0)
return nil
}