How to format timestamp in outgoing JSON

后端 未结 4 1934
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 18:11

I\'ve been playing with Go recently and it\'s awesome. The thing I can\'t seem to figure out (after looking through documentation and blog posts) is how to get the tim

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 18:34

    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/

提交回复
热议问题