Working with DB datetime/date columns in Go
This post shows how to work with DATETIME`` /
DATEdatabase columns and use Go standard
time.Timeavoiding manual string parsing. This article contains examples using 2 packages:
database/sqland
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=tru
e does not automatically convert the MySQL TIME
column type to time.Time
. The TIM
E 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.
Feedback
As always, please reach out to me on X with questions, corrections, or ideas!