这是我的表结构

type PharrCompany struct {
    Id        int32        `json:"id" gorm:"primarykey;column:id"`
    CompanyId int32        `json:"company_id" gorm:"column:company_id"`
    BeginTime sql.NullTime `json:"begin_time" gorm:"column:begin_time"`
    EndTime   sql.NullTime `json:"end_time" gorm:"column:end_time"`
}

func (*PharrCompany) TableName() string {
    return "pharr_company"
}

我创建一条数据

       dns := fmt.Sprintf(
        "%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
        user,
        password,
        host,
        port,
        dbName,
    )
    db, _ := gorm.Open(
        mysql.Open(dns),
        &gorm.Config{
            Logger: logger.Default.LogMode(logger.Info),
        },
    )
    beginTimeStr := "2021-01-01 00:00:00"
    parseBeginTime, _ := time.Parse("2006-01-02 15:04:05", beginTimeStr)
    beginTime := sql.NullTime{Time: parseBeginTime, Valid: true}
    db.Create(
        &PharrCompany{
            CompanyId: 1,
            BeginTime: beginTime,
            EndTime:   sql.NullTime{Valid: false},
        },
    )

这是打印的创建语句 Gorm sql.NullTime时区问题

可是数据存储的却是 2021-01-01 08:00:00

Gorm sql.NullTime时区问题

我本地的时区是Asia/Shanghai 我只有使用一下方式才能得到正确的结果

        loc, err := time.LoadLocation("Asia/Shanghai")
    if err != nil {
        return
    }
    parseBeginTime, err := time.ParseInLocation("2006-01-02 15:04:05", beginTimeStr, loc)
    if err != nil {
        return
    }

Comment From: github-actions[bot]

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking

Comment From: hengyumo

parseBeginTime, _ := time.Parse("2006-01-02 15:04:05", beginTimeStr)

这边没有带时区的话,入库的时候会当做 2021-01-01 00:00:00,是UTC时区。 要改成 parseBeginTime, _ := time.ParseInLocation("2006-01-02 15:04:05", beginTimeStr, time.Local)

Comment From: github-actions[bot]

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking