Gorm 格式化时间这样处理可行不可行

56 天前
 yekern
时间结构体
type UseDateTime struct {
  	CreatedAt    *time.Time `json:"-"`
	CreatedAtStr string     `json:"created_at" gorm:"-"`
	UpdatedAt    *time.Time `json:"-"`
	UpdatedAtStr string     `json:"updated_at" gorm:"-"`
}

结构体多添加两个字段 CreatedAtStrUpdatedAtStr用 Tag 来控制不参与存储

使用 Gorm 自带的 Hook AfterFind

func (u *UseDateTime) AfterFind(tx *gorm.DB) (err error) {
	if u.CreatedAt != nil {
		u.CreatedAtStr = u.CreatedAt.Format("2006-01-02 15:04:05")
	}
	if u.UpdatedAt != nil {
		u.UpdatedAtStr = u.UpdatedAt.Format("2006-01-02 15:04:05")
	}
	return
}

最终输出

{
  "code": 200,
  "data": [
    {
      "id": 1,
      "username": "admin",
      "created_at": "2019-10-29 00:28:05",
      "updated_at": "2024-06-13 14:09:15"
    }
  ]
}
1047 次点击
所在节点    Go 编程语言
4 条回复
CEBBCAT
56 天前
楼主可以同时考虑这几种方案:
1. 定义响应专用的结构体。如果嫌麻烦,可以找找看代码生成器
2. 返回 unix 时间戳
CEBBCAT
56 天前
另外 V2EX 似乎不让用别人照片当头像(以 /settings/avatar 为准)
yekern
56 天前
@CEBBCAT 感谢提醒!
highFreqSurfer
56 天前
给 time.Time 定义个别名, 实现 MarshalJSON() ([]byte, error) Scan(value interface{}) error Value() (driver.Value, error) 三个函数, 然后用这个别名替换掉你 model 里的*time.Time 就好了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1059187

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX