From 0b54c8035594e6db5bd1e2420b60066d9028502f Mon Sep 17 00:00:00 2001 From: Tulir Asokan Date: Fri, 13 Oct 2023 11:10:14 +0300 Subject: [PATCH] Add UnixMicro helper --- jsontime/jsontime.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/jsontime/jsontime.go b/jsontime/jsontime.go index b328233..9220f61 100644 --- a/jsontime/jsontime.go +++ b/jsontime/jsontime.go @@ -48,6 +48,39 @@ func (um *UnixMilli) UnmarshalJSON(data []byte) error { return nil } +func UMicro(time time.Time) UnixMicro { + return UnixMicro{Time: time} +} + +func UnixMicroNow() UnixMicro { + return UMicro(time.Now()) +} + +type UnixMicro struct { + time.Time +} + +func (um UnixMicro) MarshalJSON() ([]byte, error) { + if um.IsZero() { + return []byte{'0'}, nil + } + return json.Marshal(um.UnixMicro()) +} + +func (um *UnixMicro) UnmarshalJSON(data []byte) error { + var val int64 + err := json.Unmarshal(data, &val) + if err != nil { + return err + } + if val == 0 { + um.Time = time.Time{} + } else { + um.Time = time.UnixMicro(val) + } + return nil +} + func U(time time.Time) Unix { return Unix{Time: time} }