How to format timestamp in outgoing JSON

后端 未结 4 1945
佛祖请我去吃肉
佛祖请我去吃肉 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:55

    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.

提交回复
热议问题