datatypes icon indicating copy to clipboard operation
datatypes copied to clipboard

datatypes.Date to time.Time

Open saul-data opened this issue 3 years ago • 2 comments

Your Question

In the documentation it talks about how to go from time.Time to datatypes.Date() - insert a time into database.

Reference: https://github.com/go-gorm/datatypes/ https://github.com/go-gorm/datatypes/blob/master/date.go

But to retrieve a date from the database and convert to time.Time, I searched quite a lot and tried different methods to go from datatypes.Date() to time.Time.

I got this to work but I'm sure its probably not the best method.

x, _ :=  dbrecord.Date.MarshalJSON()
bDate, _ := time.Parse(time.RFC3339, strings.Trim(string(x), "\""))

The document you expected this should be explained

https://github.com/go-gorm/datatypes/

Expected answer

It would be good to have best practice in the readme on how to do this.

saul-data avatar Sep 23 '21 01:09 saul-data

I found another way of converting datatypes.Date to time.Time. You can do:

dVal, _ := dbRecord.Date.Value()
d := dVal.(time.Time)

EDIT: Only use this if you only care about the date part. The time gets removed.

seanballais avatar Nov 09 '21 08:11 seanballais

This seems to work:

t := time.Time(dbRecord.Date)

Go 1.20

glebtv avatar May 05 '23 15:05 glebtv