在DSN中需要加入parseTime=true&&loc=Local
,或
charset=utf8mb4&loc=Asia%2FShanghai&parseTime=true
。
go
package main_test
import (
"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 Student
for 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"))
}
}