Working with DB datetime/date columns in Go
This post shows how to work with DATETIME / DATE database columns and use Go standard time.Time avoiding manual string parsing. This article contains examples using 2 packages: database/sql and github.com/go-sql-driver/mysql.
Retrieve nullable time field using NullTime type
MySQL, PostgreSQL drivers in Go provide this nullable type which represents a time.Time that may be NULL. NullTime implements the Scanner interface so it can be used as a scan destination:
|
|
Use parseTime=true
You can ask the driver to scan DATE and DATETIME automatically to time.Time, by adding parseTime=true to your connection string (DSN).
|
|
Limitation: TIME column type
Note that parseTime=true does not automatically convert the MySQL TIME column type to time.Time. The TIME type represents a time of day or duration, not a full timestamp. You should scan TIME columns into []byte or string and handle the parsing manually if needed.