【问题标题】:How to define date in GORM如何在 GORM 中定义日期
【发布时间】:2020-03-31 15:58:59
【问题描述】:

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

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",没用

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    在 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 作为日期

    【讨论】:

    • 你好@Eklavya。我是新来的,正在探索这个 ORM。在您的第二个代码块中,您是想说我必须手动执行吗?
    • @NoobCoder 是的,需要手动解析。现在您可以使用 gorm github.com/go-gorm/datatypes#date 的自定义日期类型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多