ocuparedu
ocuparedu

Reputation: 71

retrieving datetime from mysql in time.time in golang

i have stored on my database (mySQL) this datatime field, last_activity: 2017-06-12 11:07:09

im using the param parseTime=True on my OpenDB

the problem is that the output is: last activity: {63632862429 0 <nil>} instead of 2017-06-12 11:07:09

what am i doing wrong?

thanks

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)

}

Upvotes: 3

Views: 7878

Answers (2)

kakkoko
kakkoko

Reputation: 321

You must declare DateType.String() method like this:

func (t DateType) String() string {
    return time.Time(t).String()
}

From Language Specification:

The declared type does not inherit any methods bound to the existing type

Upvotes: 3

Antony360
Antony360

Reputation: 1

time.Time is a nullable type. You got to anticipate that and use somethink like the pq package and the NullTime type instead of time.Time. cf : https://godoc.org/github.com/lib/pq#NullTime

pq.NullTime is a structure :

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

If Valid is True then you'll got a result in Time.

Upvotes: 0

Related Questions