Skip to content

Instantly share code, notes, and snippets.

@wjkoh
Created November 12, 2025 08:52
Show Gist options
  • Select an option

  • Save wjkoh/b3f44a08bd778679a16bbc566256dd94 to your computer and use it in GitHub Desktop.

Select an option

Save wjkoh/b3f44a08bd778679a16bbc566256dd94 to your computer and use it in GitHub Desktop.
Go: How to Unmarshal Unix Time from JSON Correctly
type UnixTime struct{ time.Time }
func (t *UnixTime) UnmarshalJSON(b []byte) error {
if string(b) == "null" {
t.Time = time.Time{}
return nil
}
var value any
if err := json.Unmarshal(b, &value); err != nil {
return err
}
var timestamp float64
switch v := value.(type) {
case float64:
timestamp = v
case string:
var err error
timestamp, err = strconv.ParseFloat(v, 64)
if err != nil {
return err
}
default:
return fmt.Errorf("UnixTime: cannot unmarshal JSON value of type %T", v)
}
seconds, subseconds := math.Modf(timestamp)
nanoseconds := int64(subseconds * 1e9)
t.Time = time.Unix(int64(seconds), nanoseconds)
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment