一: 定义当前默认时间,写放数据库:
Go
type Time time.Time
const (
timeFormart = "2006-01-02 15:04:05"
//timeFormart2 = "20060102150405"
)
func (t *Time) UnmarshalJSON(data []byte) (err error) {
strData := string(data)
if strings.Contains(strData, "/") {
strData = strings.Trim(strData, `"'`)
s := strings.Split(strData, "/")
formatData := `"` + s[2][:4] + "-" + s[0] + "-" + s[1] + s[2][4:] + `"`
strData = strings.Clone(formatData)
}
now, err := time.ParseInLocation(`"`+timeFormart+`"`, strData, time.Local)
*t = Time(now)
return
}
func (t Time) MarshalJSON() ([]byte, error) {
b := make([]byte, 0, len(timeFormart)+2)
b = append(b, '"')
b = time.Time(t).AppendFormat(b, timeFormart)
b = append(b, '"')
return b, nil
}
func (t Time) String() string {
return time.Time(t).Format(timeFormart)
}
func GetNow() Time {
loc, _ := time.LoadLocation("Asia/Shanghai")
return Time(time.Now().In(loc))
}
// 直接调用 GetNow() // 得出当前时间,是以 time 类型,在结构体调用:Getnow 如下结构体:
LoadTime utils.Time `json:"load_time" gorm:"type:timestamp;default:now()"`
第二种:返回当前时间类型,定义的是 Time 类型
Go
type Time time.Time
const (
timeFormart = "2006-01-02 15:04:05"
)
func (t *Time) UnmarshalJSON(data []byte) (err error) {
strData := string(data)
if strings.Contains(strData, "/") {
strData = strings.Trim(strData, `"'`)
s := strings.Split(strData, "/")
formatData := `"` + s[2][:4] + "-" + s[0] + "-" + s[1] + s[2][4:] + `"`
strData = strings.Clone(formatData)
}
now, err := time.ParseInLocation(`"`+timeFormart+`"`, strData, time.Local)
*t = Time(now)
return
}
func (t Time) MarshalJSON() ([]byte, error) {
b := make([]byte, 0, len(timeFormart)+2)
b = append(b, '"')
b = time.Time(t).AppendFormat(b, timeFormart)
b = append(b, '"')
return b, nil
}
func (t Time) String() string {
return time.Time(t).Format(timeFormart)
}
func GetNow(t time.Time) Time {
loc, _ := time.LoadLocation("Asia/Shanghai")
return Time(t.In(loc))
}
// GetNow() // 里面参数调用的是 返回 回来的时间类型处理
按这个方法调用返回时间类型: GetNow(v.CreatedAt)