How to format timestamp in outgoing JSON

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

    But I'm not really sure how, I know I can add json:stamp to the Document type declaration to get the field to be encoded with the name stamp instead of Stamp, but I don't know what those types of things are called, so I'm not even sure what to google for to find out if there is some type of formatting option in that as well.

    You mean tags. But these won't help you with your formatting problem.

    The string representation you get for your time is returned by MarshalJSON implemented by Time.

    You can go ahead and implement your own MarshalJSON method by copying the relevant bits from the Time implementation by either embedding time.Time or wrapping it. Wrapping example (Click to play):

    type ShortDateFormattedTime time.Time
    
    func (s ShortDateFormattedTime) MarshalJSON() ([]byte, error) {
        t := time.Time(s)
        if y := t.Year(); y < 0 || y >= 10000 {
            return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]")
        }
    
        return []byte(t.Format(`"Jan 02, 2006"`)), nil
    }
    

提交回复
热议问题