Last active
January 13, 2025 02:16
-
-
Save alextanhongpin/3b6b2ee47665ac9c1c32c805b86380a6 to your computer and use it in GitHub Desktop.
JavaScript timestamp to golang time.Time
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
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"strconv" | |
"strings" | |
"time" | |
) | |
type MyJsonTime struct { | |
time.Time | |
} | |
func (m *MyJsonTime) UnmarshalJSON(b []byte) error { | |
if i, err := strconv.ParseInt(string(b[1:len(b)-1]), 10, 64); err != nil { | |
return err | |
} else { | |
fmt.Println(i) | |
*m = MyJsonTime{Time: time.Unix(i/1000, (i%1000)*1000*1000)} | |
return nil | |
} | |
} | |
func main() { | |
someJSON := `{"foo":"1498891325771"}` | |
var x struct { | |
Foo *MyJsonTime `json:"foo"` | |
} | |
if err := json.Unmarshal([]byte(someJSON), &x); err != nil { | |
panic(err) | |
} | |
fmt.Println(x.Foo.Format(time.RFC3339Nano)) | |
_ = json.NewDecoder(strings.NewReader(someJSON)).Decode(&x) | |
fmt.Println(x) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment