This is a creation in Article, where the information may have evolved or changed.
Recently, a company project was developed, and when the go language structure JSON conversion was found, there was a different time format. Looking for a long time on the internet did not find a good plan. That is, the format of the structure after serialization is ' 1993-01-01t20:08:23.000000028+08:00 '. But in order to be compatible with the company's previous projects, we hope to follow the ' 1993-01-01 20:08:23 ' format. The following code has been found online to solve most of the problems.
import "time"const ( DateFormat = "2006-01-02" TimeFormat = "2006-01-02 15:04:05")type Time time.Timefunc Now() Time { return Time(time.Now())}func (t *Time) UnmarshalJSON(data []byte) (err error) { now, err := time.ParseInLocation(`"`+TimeFormat+`"`, string(data), time.Local) *t = Time(now) return}func (t Time) MarshalJSON() ([]byte, error) { b := make([]byte, 0, len(TimeFormat)+2) b = append(b, '"') b = time.Time(t).AppendFormat(b, TimeFormat) b = append(b, '"') return b, nil}func (t Time) String() string { return time.Time(t).Format(TimeFormat)}
However, this will have an effect on the original struct and will need to be the original time. The variable type of time is replaced by time. Can not be used in some ORM, such as the Beego ORM will be error. Therefore, to replace the original time format without changing the structure's time type. Just like the code above, the Marshaljson and Unmarshaljson methods are also implemented for structs.
Type User struct {id int ' JSON: ' id ' ' name ' string ' JSON: ' name ' ' Createdat time. Time ' JSON: ' Created_at ' '}func (U *user) Marshaljson () ([]byte, error) {type Alias user user: = &struct { Createdat time ' JSON: "Created_at" ' *alias}{time (U.createdat), (*alias) (U)} return JSON. Marshal (user)}func (u *user) unmarshaljson (data []byte) (err error) {Type Alias user user: = &struct {C Reatedat time ' json: ' created_at ' ' *alias}{time (U.createdat), (*alias) (u)} err = json. Unmarshal (data, user) if err! = Nil {return err} user. Alias.createdat = time. Time (user. Createdat) *u = User (*user. Alias) return Nil}func main () {var user *user user = &user{id:4, Name: "Liam", Create Dat:time. Now (),} bytes, _: = json. Marshal (user) fmt. Printf ("%v\n", string (bytes)) Data: = ' {' id ': 3, ' name ': ' Liam Lian ', ' created_at ': ' 2017-11-18 19:00:00 '} ' json. Unmarshal ([]byte (data), &user) fmt. Printf ("%v\n", user)}
This enables the compatibility of time formats without affecting the original structure. But if such a structure is more, there will be a lot of this kind of code. No perfect solution has been found yet.