// UnmarshalJSON implements the json.Unmarshaler interface. // The time is expected to be a quoted string in RFC 3339 format. func(t *Time)UnmarshalJSON(data []byte)error { // Ignore null, like in the main JSON package. ifstring(data) == "null" { returnnil } // Fractional seconds are handled implicitly by Parse. var err error *t, err = Parse(`"`+RFC3339+`"`, string(data)) return err }
type Hoge struct { Created JSONTime `json:"created"` }
// JSONTime exists so that we can have a String method converting the date type JSONTime string
// String converts the unix timestamp into a string func(t JSONTime)String()string { tm := t.Time() return fmt.Sprintf("\"%s\"", tm.Format(time.RFC3339)) }
// Time returns a `time.Time` representation of this value. func(t JSONTime)Time()time.Time { tt, _ := time.Parse(time.RFC3339, string(t)) return tt }
// UnmarshalJSON will unmarshal both string and int JSON values func(t *JSONTime)UnmarshalJSON(buf []byte)error { s := bytes.Trim(buf, `"`) *t = JSONTime(string(s)) returnnil }
funcmain() { var hoge Hoge j := []byte(`{"created": "1981-01-07T17:44:13Z"}`) if err := json.Unmarshal(j, &hoge); err != nil { log.Fatal(err) } t := hoge.Created fmt.Println(t) // "1981-01-07T17:44:13Z" fmt.Println(t.Time()) // 1981-01-07 17:44:13 +0000 UTC }