Skip to content

Commit

Permalink
Add UnixMicro helper
Browse files Browse the repository at this point in the history
  • Loading branch information
tulir committed Oct 13, 2023
1 parent 274c218 commit 0b54c80
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions jsontime/jsontime.go
Original file line number Diff line number Diff line change
Expand Up @@ -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}
}
Expand Down

0 comments on commit 0b54c80

Please sign in to comment.