-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdate.go
More file actions
36 lines (29 loc) · 888 Bytes
/
date.go
File metadata and controls
36 lines (29 loc) · 888 Bytes
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
package jsonutil
import (
"encoding/json/jsontext"
"encoding/json/v2"
"time"
"cloud.google.com/go/civil"
)
// DateMarshalIntUnix is a custom marshaler for civil.Date, marshaling them as integers representing unix time.
func DateMarshalIntUnix(enc *jsontext.Encoder, d civil.Date) error {
if d.IsZero() {
return enc.WriteToken(jsontext.Int(0))
}
return enc.WriteToken(jsontext.Int(int64(
time.Date(d.Year, d.Month, d.Day, 0, 0, 0, 0, time.UTC).Unix(),
)))
}
// DateUnmarshalIntUnix is a custom unmarshaler for civil.Date, unmarshaling them from integers and assuming they represent unix time.
func DateUnmarshalIntUnix(dec *jsontext.Decoder, d *civil.Date) error {
var seconds int64
if err := json.UnmarshalDecode(dec, &seconds); err != nil {
return err
}
if seconds == 0 {
*d = civil.Date{}
} else {
*d = civil.DateOf(time.Unix(seconds, 0))
}
return nil
}