How to Parse MySQL Time Data in Golang?

Mary-Kate Olsen
Release: 2024-11-21 05:29:14
Original
985 people have browsed it

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)
Copy after login

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")
Copy after login

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))
}
Copy after login

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())
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template