1
wfhtqp 2021-08-16 14:03:24 +08:00
自定义类型并实现 Unmarshal/Marshal 方法
|
2
danc 2021-08-17 00:47:40 +08:00
```go
package util import "time" func ParseTime(value string) (time.Time, error) { loc := time.FixedZone("UTC+8", +8*60*60) return time.ParseInLocation("2006-01-02 15:04:05", value, loc) } func TimeFormat(t time.Time) string { loc := time.FixedZone("UTC+8", +8*60*60) return t.In(loc).Format("2006-01-02 15:04:05") } type MyTime time.Time func (myT MyTime) MarshalText() (data []byte, err error) { t := time.Time(myT) data = []byte(TimeFormat(t)) return } func (myT *MyTime) UnmarshalText(text []byte) (err error) { t := (*time.Time)(myT) *t, err = ParseTime(string(text)) return } ``` 然后 ```go type MonitorDiagnosisItem struct { Time util.MyTime `json:"time"` } ``` 学会了吗? |
3
hunk OP 好详细,谢谢。我用了两个 struct 做转换,回头试试这种写法
|