Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format timestamp in outgoing JSON

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 time.Time type to format into whatever format I'd like when it's encoded by json.NewEncoder.Encode

Here's a minimal Code example:

package main  type Document struct {     Name        string     Content     string     Stamp       time.Time     Author      string }  func sendResponse(data interface{}, w http.ResponseWriter, r * http.Request){      _, err := json.Marshal(data)     j := json.NewEncoder(w)     if err == nil {         encodedErr := j.Encode(data)         if encodedErr != nil{             //code snipped         }     }else{        //code snipped     } }  func main() {     http.HandleFunc("/document", control.HandleDocuments)     http.ListenAndServe("localhost:4000", nil) }  func HandleDocuments(w http.ResponseWriter,r *http.Request) {     w.Header().Set("Content-Type", "application/json")     w.Header().Set("Access-Control-Allow-Origin", "*")      switch r.Method {         case "GET":              //logic snipped             testDoc := model.Document{"Meeting Notes", "These are some notes", time.Now(), "Bacon"}                 sendResponse(testDoc, w,r)             }         case "POST":         case "PUT":         case "DELETE":         default:             //snipped     } } 

Ideally, I'd like to send a request and get the Stamp field back as something like May 15, 2014 and not 2014-05-16T08:28:06.801064-04:00

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.

Does anyone have a link to the an example or good documentation page on the subject of those type mark ups (or whatever they're called) or on how I can tell the JSON encoder to handle time.Time fields?

Just for reference, I have looked at these pages: here and here and of course, at the official docs

like image 783
EdgeCaseBerg Avatar asked May 16 '14 12:05

EdgeCaseBerg


People also ask

What is JSON time format?

JSON does not have a built-in type for date/time values. The general consensus is to store the date/time value as a string in ISO 8601 format. Example { "myDateTime": "2018-12-10T13:45:00.000Z" }

How do I pass a date field in JSON?

You can get the value of the date field as String by calling the getText() method of JsonParser class and then you can simply convert it into a Date object by using the parse() method of SimpleDateFormat, as you normally parse Date in Java.

Does JSON support date format?

JSON does not directly support the date format and it stores it as String. However, as you have learned by now that mongo shell is a JavaScript interpreter and so in order to represent dates in JavaScript, JSON uses a specific string format ISODate to encode dates as string.

Does JSON accept DateTime?

Json library parses and writes DateTime and DateTimeOffset values according to the ISO 8601-1:2019 extended profile.


2 Answers

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.

like image 117
Not_a_Golfer Avatar answered Oct 05 '22 03:10

Not_a_Golfer


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/

like image 42
s7anley Avatar answered Oct 05 '22 04:10

s7anley