..."/> ...">
Home >Backend Development >Golang >How to Parse MySQL Time Data in Golang?
MySQL Time Parsing in Golang
In Golang, fetching time data from MySQL can pose a challenge, as exemplified by the error "unsupported driver -> Scan pair: []uint8 -> *time.Time" when using the code snippet below:
var my_time time.Time rows, err := db.Query("SELECT current_time FROM table") err := rows.Scan(&my_time)
To resolve this issue, consider using the go-sql-driver/mysql driver, which offers the option to automatically convert DATE and DATETIME data types to time.Time. This can be achieved by adding parseTime=true to the connection string, as demonstrated below:
db, err := sql.Open("mysql", "root:@/?parseTime=true")
However, if you specifically require current_time (rather than current_timestamp), you will need to manually parse the time data. Below are two approaches to achieve this:
Custom Time Parsing Type
Create a custom type, rawTime, that encapsulates a []byte slice and provides a Time() method for time parsing:
type rawTime []byte func (t rawTime) Time() (time.Time, error) { return time.Parse("15:04:05", string(t)) }
In your scanning code, use rawTime to automatically parse the current_time:
var myTime rawTime rows, err := db.Query("SELECT current_time()") if rows.Next() { if err = rows.Scan(&myTime); err != nil { panic(err) } } fmt.Println(myTime.Time())
Manual Time Parsing
Instead of relying on a custom type, you can manually parse the time data:
var myTime string rows, err := db.Query("SELECT current_time()") if rows.Next() { if err = rows.Scan(&myTime); err != nil { panic(err) } } parsedTime, err := time.Parse("15:04:05", myTime) if err != nil { panic(err) } fmt.Println(parsedTime)
The above is the detailed content of How to Parse MySQL Time Data in Golang?. For more information, please follow other related articles on the PHP Chinese website!