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

31,338

Solution 1

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.

Solution 2

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.

Share:
31,338

Related videos on Youtube

Yuliang Li
Author by

Yuliang Li

Welcome to my blog! https://liyuliang.cc/

Updated on May 20, 2021

Comments

  • Yuliang Li
    Yuliang Li almost 3 years

    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?

  • Yuliang Li
    Yuliang Li over 5 years
    So it need a process to convert the attribute format?
  • Yuliang Li
    Yuliang Li over 5 years
    can protobuf define the attribute time.Time type in message?
  • colm.anseo
    colm.anseo almost 5 years
    In short, yes. A protobuf timestamp has no timezone info. Go's time.Time does. So one would need to add zoneinfo to any message alongside the timestamp. However, since protobuf is mainly used with micro-services & not usually user-facing, maintaining zoneinfo at a micro-service level is most likely not needed.
  • TehSphinX
    TehSphinX about 3 years
    This answer is outdated. The function is deprecated.
  • Cosmic Ossifrage
    Cosmic Ossifrage almost 3 years
    @TehSphinX thanks, updated the answer to refer to APIv2 approach.