当前位置:网站首页>Go project practice - Gorm format time field

Go project practice - Gorm format time field

2022-07-05 10:39:00 Golang Chinese community

### goshop Update of open source projects > remarks : The code used in the previous project has been shared GitHub In the , And the codes that will appear in all projects in the future will be submitted , Welcome to consult . If you are interested, you can order star Oh ~ https://gitee.com/jobhandsome/goshop/ In the use of `gorm` When inquiring , If the time field is not processed , The field type in the structure is `time.Time` :```gotype Model struct { ID int64 `json:"id" gorm:"primary_key"` CreatedAt *time.Time `json:"created_at"` UpdatedAt *time.Time `json:"updated_at"` DeletedAt *time.Time `json:"deleted_at" sql:"index"`}``` Here we use `time.Time` Type in the `gorm` Return result of query , The time field read is often like this :"`2022-07-03T22:14:02.973528+08:00`", With time zone and milliseconds . But in fact, it is often in this format , Not what we want .#### So here's the problem :1. If you want to "`2022-07-03 22:14:02`" This format , How to deal with it ?2. When inserting a piece of data into the corresponding table ,`UpdateAt` Fields are not assigned , Inserting into the database will `0001-01-01 00:00:00.000000+00:00`, The system is endowed with ⼀ Default values , When you don't want to insert ⼊` The default value is ` How to deal with ?#### Through the above analysis , We can identify two needs :1. The read time needs to be :"2022-07-03 22:14:02" This format 2. When the time field is not assigned , Do not insert default values #### resolvent :##### Define a time type `struct````gotype LocalTime time.Time``` Although the actual type of this data type is `time.Time`, But not `time.Time` The built-in ⽅ Law , Need to rewrite `MarshalJSON` ⽅ Method to realize data analysis ```gofunc (t *LocalTime) MarshalJSON() ([]byte, error) { tTime := time.Time(*t) return []byte(fmt.Sprintf("\"%v\"", tTime.Format("2006-01-02 15:04:05"))), nil}```> Be careful :`GO` The specified time string of the format time of must be `2006-01-02 15:04:05` This is a `GO` Birthday ⽣ Time , Cannot change to another time ( This time string is related to `java` Of "`yyyy-MM-dd HH:mm:ss`") CO production ⽤ take `time.Time` Replace with `LocalTime````gotype Model struct { ID int64 `json:"id" gorm:"primary_key"` CreatedAt *LocalTime `json:"created_at"` UpdatedAt *localTime `json:"updated_at"` DeletedAt *localTime `json:"deleted_at" sql:"index"`}``` At this step, the first requirement is to format the time data when reading the data .##### Let's implement the second requirement :```gofunc (t LocalTime) Value() (driver.Value, error) { var zeroTime time.Time tlt := time.Time(t) // Judge whether the given time is the same as the timestamp of the default zero time if tlt.UnixNano() == zeroTime.UnixNano() { return nil, nil } return tlt, nil}````Value`⽅ The method is to adjust when storing ⽤, Will be ⽅ The return value of method goes into ⾏ Storage , The ⽅ Method can realize the data processing before data storage ⾏ The relevant operation .```gofunc (t *LocalTime) Scan(v interface{}) error { if value, ok := v.(time.Time); ok { *t = LocalTime(value) return nil } return fmt.Errorf("can not convert %v to timestamp", v)}````Scan`⽅ Method can be used to query data before it is found ⾏ The relevant operation . Here we are , We have achieved the functions required above . For more features, please continue to pay attention to !!!!!#### Planet address :https://t.zsxq.com/03MJM7YfI#### ** Official account 「 Programmer Joe 」**![ Programmer Joe ](https://www.qsjob.fun/zb_users/upload/2022/07/202207041451541741109.jpg " Programmer Joe ")
原网站

版权声明
本文为[Golang Chinese community]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207051011239089.html