在 Golang 中从 MySQL 检索时间戳的日期时间。

3
我已经在我的数据库(mySQL)中存储了这个日期时间字段,最后活动时间:2017年6月12日11:07:09。
我在OpenDB中使用参数parseTime=True。
问题是输出结果为:last activity: {63632862429 0 },而不是2017年6月12日11:07:09。
我做错了什么?
谢谢。
type DateType time.Time

type User struct {
    LastActivity DateType
}


func (stUser *User) GetUserDataByLogin(login string) {

db := OpenDB()

defer db.Close()

// Test the connection to the database
err := db.Ping()
checkErr(err)

err = db.QueryRow("SELECT  last_activity FROM users WHERE login = ?", login).Scan(&stUser.LastActivity)

if err != nil {
    if err == sql.ErrNoRows {
        // there were no rows, but otherwise no error occurred
    } else {
        log.Fatal(err)
    }
}

fmt.Println("last activity:", stUser.LastActivity)

}

2个回答

3
您需要像这样声明 DateType.String() 方法:
func (t DateType) String() string {
    return time.Time(t).String()
}

来自语言规范

声明的类型不会继承任何绑定到现有类型的方法。


0

time.Time 是一个可空类型。你必须预先考虑到这一点,并使用类似于 pq 包和 NullTime 类型而不是 time.Time。 参考链接:https://godoc.org/github.com/lib/pq#NullTime

pq.NullTime 是一个结构体:

type NullTime struct {
    Time  time.Time
    Valid bool // Valid is true if Time is not NULL
}

如果ValidTrue,那么你将会在Time中得到一个结果。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接