Skip to content

Instantly share code, notes, and snippets.

@edsrzf
Created November 7, 2011 20:43
Show Gist options
  • Save edsrzf/1346113 to your computer and use it in GitHub Desktop.
Save edsrzf/1346113 to your computer and use it in GitHub Desktop.
Unmarshaling time string with json
type Timestamp int64
func (ts *Timestamp) UnmarshalJSON(data []byte) os.Error {
if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' {
return os.NewError("cannot unmarshal non-string into timestamp")
}
data = data[1 : len(data)-1]
t, err := time.Parse(time.RFC3339, string(data))
if err != nil {
return err
}
*ts = Timestamp(t.Nanoseconds())
return nil
}
func (ts Timestamp) MarshalJSON() ([]byte, os.Error) {
t := time.NanosecondsToUTC(int64(ts))
return []byte(`"` + t.Format(time.RFC3339) + `"`), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment