Skip to content

time zone will be lost when using db.Exec() to create columns containing time #146

@cyberxnomad

Description

@cyberxnomad

When using db.Create() to create a column containing the time, it will contain the time zone

type Example struct {
	Id        int `gorm:"primaryKey;autoIncrement;"`
	CreatedAt time.Time
	UpdatedAt time.Time
	Name      string
}

func main() {
	db, err := gorm.Open(sqlite.Open("test.db"))
	if err != nil {
		panic(err)
	}

	db.AutoMigrate(new(Example))

	example := Example{Name: "Tome"}

	db.Debug().Create(&example)
}
[37.259ms] [rows:1] INSERT INTO `examples` (`created_at`,`updated_at`,`name`) VALUES ("2024-10-23 10:53:07.42","2024-10-23 10:53:07.42","Tome") RETURNING `id`

image

using db.Exec()

type Example struct {
	Id        int `gorm:"primaryKey;autoIncrement;"`
	CreatedAt time.Time
	UpdatedAt time.Time
	Name      string
}

func main() {
	db, err := gorm.Open(sqlite.Open("test.db"))
	if err != nil {
		panic(err)
	}

	db.AutoMigrate(new(Example))

	now := time.Now()
	example := Example{Name: "Tome", Id: 1, CreatedAt: now, UpdatedAt: now}

	sql := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
		return tx.Create(&example)
	})

	fmt.Println("sql:", sql)

	db.Exec(sql)
}
sql: INSERT INTO `examples` (`created_at`,`updated_at`,`name`,`id`) VALUES ("2024-10-23 10:58:19.003","2024-10-23 10:58:19.003","Tome",1) RETURNING `id`

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions