VMx

vmx.im
啥都学一点的填坑人
  1. 首页
  2. golang
  3. 正文

gorm使用格式化时间

2022年4月24日 966点热度 0人点赞 0条评论

在做项目时发现gorm的时间格式是带有时区输入输出的,对平常使用的2020-01-03 12:22:33格式有一定的出入,不方便前端和后端的对接,所以自己整理一下处理这个问题方法,方便大家参考

package models

import (
    "database/sql/driver"
    "errors"
    "fmt"
    "strings"
    "time"
)

//BaseModel 基础结构体 信息信息
type BaseModel struct {
    CreateTime MyTime `gorm:"comment:'创建时间';type:timestamp;";json:"createTime"`
    UpdateTime MyTime `gorm:"comment:'修改时间';type:timestamp;";json:"updateTime"`
    Remark     string `gorm:"comment:'备注'";json:"remark"`
}
//MyTime 自定义时间
type MyTime time.Time

func (t *MyTime) UnmarshalJSON(data []byte) error {
    if string(data) == "null" {
        return nil
    }
    var err error
    //前端接收的时间字符串
    str := string(data)
    //去除接收的str收尾多余的"
    timeStr := strings.Trim(str, "\"")
    t1, err := time.Parse("2006-01-02 15:04:05", timeStr)
    *t = MyTime(t1)
    return err
}

func (t MyTime) MarshalJSON() ([]byte, error) {
    formatted := fmt.Sprintf("\"%v\"", time.Time(t).Format("2006-01-02 15:04:05"))
    return []byte(formatted), nil
}

func (t MyTime) Value() (driver.Value, error) {
    // MyTime 转换成 time.Time 类型
    tTime := time.Time(t)
    return tTime.Format("2006-01-02 15:04:05"), nil
}

func (t *MyTime) Scan(v interface{}) error {
    switch vt := v.(type) {
    case time.Time:
        // 字符串转成 time.Time 类型
        *t = MyTime(vt)
    default:
        return errors.New("类型处理错误")
    }
    return nil
}

func (t *MyTime) String() string {
    return fmt.Sprintf("hhh:%s", time.Time(*t).String())
}

https://blog.csdn.net/qq_37493556/article/details/105082422

Post Views: 805
标签: 暂无
最后更新:2022年4月24日

huifei

这个人很懒,什么都没留下

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2021 vmx.im. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang