This is a creation in Article, where the information may have evolved or changed.
Golang time format solution for JSON
1. Specify the number format when querying through the data, so you don't have to format it again.
2. Pass time. The time type wears an alias, and then implements the Marshaljson method for the alias class.
The following original comments from Golang
If an encountered value implements the Marshaler interface
and is not a nil pointer, Marshal calls its Marshaljson method
to produce JSON. If no Marshaljson method is present but the
Value implements encoding. Textmarshaler instead, Marshal calls
Its Marshaltext method.
//jsontest project Main.go PackageMainImport("Encoding/json" "FMT" "Time")typeJsontime time. Time//Implement its JSON serialization methodfunc(This jsontime) Marshaljson () ([]byte, error) {varStamp = FMT. Sprintf ("\"%s\ "", time. Time (this). Format ("2006-01-02 15:04:05"))return[]byte(stamp),Nil}typeTeststruct{Date Jsontime' JSON: ' Date 'Namestring ' JSON: ' Name 'StateBOOL ' JSON: ' state '}funcMain () {vart = test{} t.date = Jsontime (time. Now ()) T.name ="Hello World"T.state =trueBody, _: = json. Marshal (t) fmt. Println (string(body))}
Output Result:
{"date ": "2016-11-04 13:42:24" , " Name ": " Hello World " ," state ": true }