0
votes

So I have numerous structs which extend the gorm Model meaning they have createdAt, updatedAt and deletedAt time.Time fields. When I go to marshal these into JSON, the formats of the dates I receive vary. The proper RFC3339 timestamps it should produce look like:

2016-04-18T00:03:20Z

However, I am only getting dates formatted this way about 20% of the time. The remainder of the timestamps have a variable number of subseconds. I have received the following formats:

2016-04-18T05:51:11.54772087Z

2016-04-18T05:51:11.543835101Z

2016-04-18T05:53:20.1674444Z

Is there any way I can coerce Go into to giving me consistent timestamps? Thanks in advance!

1
This is not RFC3339, its RFC3339Nano, see this play.golang.org/p/7oJ_-7FmB- (run it localy, the time in playground is limited) and can you show when you get the first one and when the others? - fzerorubigd
@fzerorubigd I'm getting 2016-04-18T18:35:39-04:00 2016-04-18T18:35:39.524444112-04:00 When I run that locally. Neither of those matches the schema of the dates i'm getting from Go's json parser. Any ideas? - AttilaTheFun

1 Answers

0
votes

The best way to control the output, is writing your own type. say type MyTime time.Time and implement Marshaller and Unmarshaller for it with your formatting. see time.MarshalJSON and time.UnmarshalJSON for hint. if you need this in a database column, implement the Scanner and Valuer on that too (see this answer). for other Marshaller/Unmarshaller you need to implement their interfaces (for example yaml/gob/...)