首页 > 解决方案 > 如何在 GORM 中定义日期

问题描述

看起来 GORM 不支持 DATE 类型,定义日期的唯一方法是通过 time.Time :

type Header struct {

    Start    time.Time  `json:"period_start"`
    End      time.Time  `json:"period_end" `
    CreatedAt      time.Time `json:"created_at" sql:"DEFAULT:CURRENT_TIMESTAMP"`
    CreatedBy      string     `json:"created_by"`
    UpdatedAt      time.Time `json:"updated_at" sql:"DEFAULT:CURRENT_TIMESTAMP"`
    UpdatedBy      string     `json:"updated_by"`
}

因此创建的表将具有 TIMESTAMP 作为类型。有没有解决的办法?我试过 sql:"DATE",没用

标签: gogo-gorm

解决方案


在 Gorm 中使用time.Time类型进行定义Date

type Header struct {
    StartDate    time.Time  `json:"start_date"`
    ...
}

数据库表

CREATE TABLE `header` (
  ...
  `start_date` DATE DEFAULT NULL
)

对于解析日期字符串使用这个

format := "2006-01-02"
date, _ := time.Parse(format, "2019-07-10")

为了time.Time正确处理,您需要parseTime在连接中包含作为参数。

db, err = Open("mysql", "gorm:gorm@/gorm?charset=utf8&parseTime=True")

更新:

现在我们可以使用GORM Customized Data Types Collection for Date


推荐阅读