在DSN中需要加入parseTime=true&&loc=Local
,或
charset=utf8mb4&loc=Asia%2FShanghai&parseTime=true
。
package main_testimport ("database/sql""fmt""testing""time"_ "github.com/go-sql-driver/mysql"
)func TestMysqlDatetime(t *testing.T) {type Student struct {CreateAt time.Time}db, _ := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/test?parseTime=true&&loc=Local")rows, _ := db.Query("SELECT create_at FROM `student`")defer rows.Close()var student Studentfor rows.Next() {err := rows.Scan(&student.CreateAt)if err != nil {fmt.Printf("scan failed, err:%v\n", err)return}fmt.Println("student.CreateAt:", student.CreateAt.Format("2006-01-02 15:04:05"))}
}
参考
https://github.com/go-sql-driver/mysql#timetime-support