Formatting time in golang gorm
- 2020-07-21 08:34:15
- OfStack
preface
Recently, I encountered a problem during the development of a project.
gorm automatically maintains key time fields like created_at, updated_at, and deleted_at. But its principle and drawback need to understand 1.
1. Usage
Control the time format by customizing 1 localtime structure
package utils
import (
"time"
//"strconv"
"fmt"
"database/sql/driver"
"strconv"
)
type LocalTime struct {
time.Time
}
func (t LocalTime) MarshalJSON() ([]byte, error) {
// Format the seconds
seconds := t.Unix()
return []byte(strconv.FormatInt(seconds, 10)), nil
}
func (t LocalTime) Value() (driver.Value, error) {
var zeroTime time.Time
if t.Time.UnixNano() == zeroTime.UnixNano() {
return nil, nil
}
return t.Time, nil
}
func (t *LocalTime) Scan(v interface{}) error {
value, ok := v.(time.Time)
if ok {
*t = LocalTime{Time: value}
return nil
}
return fmt.Errorf("can not convert %v to timestamp", v)
}
The field structure of dao is
type TestDao struct{
Id uint `gorm:"primary_key,AUTO_INCREMENT" json:"id"`
CreatedAt LocalTime `json:"-"`
UpdatedAt LocalTime `json:"update_at"`
DeletedAt *LocalTime `json:"-"`
}
2. Implementation principle
This is actually done by defining the current time through the callback function when save changes. Refer to portal for this article
This allows you to control the time format through the custom LocalTime.
3. Disadvantages and Suggestions
Because fields like createAt are still of type LocalTime when the program runs, it's not easy to copy them yourself.
For example, you want to change the createAt time of the application by 1 while it is running. You can't do it! Because it's of type LocalTime, and your time is either timestamp or 1 string, the type doesn't match... Isn't it embarrassing??
Therefore, it is recommended that such reserved fields should not be modified while the program is running. Just use it as a record or identifier. If you really need to change the time, maintain the contents of the fields yourself. For example, use int to store timestamps or string to store strings. And then every time you change it, you change its value.
You can also wrap the work itself into an callback function so that you can control the field at will. Refer to portal above.
So, just to make fun of it, gorm's implementation of time formatting is so inhumane!
conclusion