-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtime.go
More file actions
70 lines (59 loc) · 1.63 KB
/
Copy pathtime.go
File metadata and controls
70 lines (59 loc) · 1.63 KB
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
package jsonutil
import (
"encoding/json/jsontext"
"encoding/json/v2"
"errors"
"fmt"
"time"
)
// TimeMarshalIntUnix is a custom marshaler for time.Time, marshaling them as integers representing unix time.
func TimeMarshalIntUnix(enc *jsontext.Encoder, t time.Time) error {
if t.IsZero() {
return enc.WriteToken(jsontext.Int(0))
}
return enc.WriteToken(jsontext.Int(int64(t.Unix())))
}
// TimeUnmarshalIntUnix is a custom unmarshaler for time.Time, unmarshaling them from integers and assuming they represent unix time.
func TimeUnmarshalIntUnix(dec *jsontext.Decoder, d *time.Time) error {
var seconds int64
if err := json.UnmarshalDecode(dec, &seconds); err != nil {
return err
}
if seconds == 0 {
*d = time.Time{}
} else {
*d = time.Unix(seconds, 0)
}
return nil
}
// TimeUnmarshalStringOrIntUnix unmarshals a time.Time from either an RFC3339
// string or an integer representing unix seconds. Nulls decode as the zero time.
func TimeUnmarshalStringOrIntUnix(dec *jsontext.Decoder, d *time.Time) error {
tkn, err := dec.ReadToken()
if err != nil {
return err
}
switch tkn.Kind() {
case jsontext.KindNumber:
if seconds := tkn.Int(); seconds == 0 {
*d = time.Time{}
} else {
*d = time.Unix(seconds, 0)
}
case jsontext.KindString:
s := tkn.String()
if err := d.UnmarshalText([]byte(s)); err != nil {
const altLayout = "Mon Jan 2 2006 15:04:05 MST-0700"
ts, err2 := time.Parse(altLayout, s)
if err2 != nil {
return errors.Join(err, err2)
}
*d = ts
}
return nil
case jsontext.KindNull: // ok, nothing to do
default:
return fmt.Errorf("unknown token kind %s", tkn.Kind())
}
return nil
}