How to format timestamp in outgoing JSON

Solution 1:

What you can do is, wrap time.Time as your own custom type, and make it implement the Marshaler interface:

type Marshaler interface {
    MarshalJSON() ([]byte, error)
}

So what you'd do is something like:

type JSONTime time.Time

func (t JSONTime)MarshalJSON() ([]byte, error) {
    //do your serializing here
    stamp := fmt.Sprintf("\"%s\"", time.Time(t).Format("Mon Jan _2"))
    return []byte(stamp), nil
}

and make document:

type Document struct {
    Name        string
    Content     string
    Stamp       JSONTime
    Author      string
}

and have your intialization look like:

 testDoc := model.Document{"Meeting Notes", "These are some notes", JSONTime(time.Now()), "Bacon"}    

And that's about it. If you want unmarshaling, there is the Unmarshaler interface too.

Solution 2:

Perhaps another way will be interesting for someone. I wanted to avoid using alias type for Time.

type Document struct {
    Name    string
    Content string
    Stamp   time.Time
    Author  string
}

func (d *Document) MarshalJSON() ([]byte, error) {
    type Alias Document
    return json.Marshal(&struct {
        *Alias
        Stamp string `json:"stamp"`
    }{
        Alias: (*Alias)(d),
        Stamp: d.Stamp.Format("Mon Jan _2"),
    })
}

Source: http://choly.ca/post/go-json-marshalling/