Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define date in GORM

Tags:

It looks like GORM doesn't have support for DATE type, the only way to define date is through 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"`
}

So created table will have TIMESTAMP as a type. Is there a way around this? I tried sql:"DATE", it didn't work

like image 410
Ripley Rip Avatar asked Mar 31 '20 15:03

Ripley Rip


1 Answers

Use time.Time type for define Date in Gorm

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

DB Table

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

For parsing date string use this

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

In order to handle time.Time correctly, you need to include parseTime as a parameter in connection.

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

Update:

Now we can use GORM Customized Data Types Collection for Date

like image 71
Eklavya Avatar answered Oct 17 '22 01:10

Eklavya