Skip to content

Instantly share code, notes, and snippets.

@alextanhongpin
Last active July 3, 2022 20:08
Show Gist options
  • Save alextanhongpin/3b6b2ee47665ac9c1c32c805b86380a6 to your computer and use it in GitHub Desktop.
Save alextanhongpin/3b6b2ee47665ac9c1c32c805b86380a6 to your computer and use it in GitHub Desktop.
JavaScript timestamp to golang time.Time
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