指尖上的记忆指尖上的记忆
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub

在实际项目中,我们经常需要输出时间,由于一般在Model类里会定义如下的字段: CreatedAt time.Time gorm:"type:timestamp;default:NULL;comment:创建时间" UpdatedAt time.Time gorm:"type:timestamp;default:NULL;comment:更新时间"

这在输出以后基本上都是如下格式: "created_at": "2022-09-08T09:29:42+08:00"

那么怎么解决这个问题,就需要通过自定义类型解决,代码如下:


//自定义时间类型
type JsonTime time.Time

func (j JsonTime) MarshalJSON() ([]byte, error) {
	var stamp = fmt.Sprintf(`"%s"`, time.Time(j).Format("2006-01-02 15:04:05"))
	return []byte(stamp), nil
}

//
type i struct {
	Id          uint              `json:"id"`
	Name        string            `json:"name"`
	CreatedAt   response.JsonTime `json:"created_at"`
}

type val struct {
	ID          uint                    `gorm:"primarykey;column:id;"`
	Name        string                  `gorm:"type:varchar(15);default:NULL;comment:名称"`
	CreatedAt   time.Time               `gorm:"type:timestamp;default:NULL;comment:创建时间"`
	UpdatedAt   time.Time               `gorm:"type:timestamp;default:NULL;comment:更新时间"`
}

i.CreatedAt = response.JsonTime(val.CreatedAt) //这里需要类型强转

//再通过json返回数据 i 的时候,就会格式化为 "2006-01-02 15:04:05" 格式