Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get time.Time in Golang protobuf v3 struct?

I'm using the google time package github.com/golang/protobuf/ptypes/timestamp in protobuf message file now.

google.protobuf.Timestamp UpdateTime = 9;

But the UpdateTime property becomes a pointer *timestamp.Timestamp in golang struct after protoc compiling, it's not a time.Time and I can't save these property into Mysql timestamp column.

What can I do?

like image 900
Yuliang Li Avatar asked Oct 14 '18 12:10

Yuliang Li


2 Answers

To obtain a time.Time from a protobuf field of type google.protobuf.Timestamp, use the AsTime method defined on the timestamppb.Timestamp type.

When producing the insert call into your database, or any other location where a time.Time is required, call myMsg.UpdateTime.AsTime() to obtain the required value (where myMsg is a variable to an instance of the relevant Protobuf message type).


This answer assumes you are using the new Protobuf APIv2 interface, defined in the google.golang.org/protobuf package, or that you are using the APIv2-compatible implementation of APIv1, defined in package github.com/golang/protobuf at version v1.20 or greater.

Many projects are still to update to these versions. It is highly recommended that you look to upgrade your code generation and toolchain to benefit from new functionality.

like image 185
Cosmic Ossifrage Avatar answered Sep 25 '22 17:09

Cosmic Ossifrage


The AsTime method can be used to convert a Timestamp message to a standard Go time.Time value in UTC:

t := ts.AsTime()
... // make use of t as a time.Time

The AsTime method performs the conversion on a best-effort basis. Timestamps with denormal values (e.g., nanoseconds beyond 0 and 99999999, inclusive) are normalized during the conversion to a time.Time. To manually check for invalid Timestamps per the documented limitations in timestamp.proto, additionally call the CheckValid method:

if err := ts.CheckValid(); err != nil {
    ... // handle error
}

This is documented in timestamppb package.

like image 28
ignite Avatar answered Sep 24 '22 17:09

ignite