As Zeebo inspired the answer and hashed in the comments on this answer:
http://play.golang.org/p/pUCBUgrjZC
package main import "fmt" import "time" import "encoding/json" type jsonTime struct { time.Time f string } func (j jsonTime) format() string { return j.Time.Format(jf) } func (j jsonTime) MarshalText() ([]byte, error) { return []byte(j.format()), nil } func (j jsonTime) MarshalJSON() ([]byte, error) { return []byte(`"` + j.format() + `"`), nil } func main() { jt := jsonTime{time.Now(), time.Kitchen} if jt.Before(time.Now().AddDate(0, 0, 1)) {
This solution inserts time. Time to jsonTime structure. Embedding supports all the time. Temporary methods for the jsonTime structure that allow you to use them without explicit type conversion (see // 1).
Embedding time. Time also has a way to advance the MarshalJSON method, which encodes the / json encoding code for priorities higher than the MarshalText method for backward compatibility reasons ( MarshalText was added in Go 1.2 , MarshalJSON precedes this). As a result, the default format time.Time is used instead of the custom format provided by MarshalText.
To overcome this problem, we will redefine MarshalJSON for structure jsonTime.
Chrish
source share