Created
November 12, 2025 08:52
-
-
Save wjkoh/b3f44a08bd778679a16bbc566256dd94 to your computer and use it in GitHub Desktop.
Go: How to Unmarshal Unix Time from JSON Correctly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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