如何在 Golang protobuf v3 结构中获取 time.Time?

Yul*_* Li 18 mysql timestamp go protocol-buffers

我现在github.com/golang/protobuf/ptypes/timestamp在 protobuf 消息文件中使用谷歌时间包。

google.protobuf.Timestamp UpdateTime = 9;
Run Code Online (Sandbox Code Playgroud)

但是这个UpdateTime属性*timestamp.Timestamp在protoc编译后变成了golang struct中的一个指针,它不是atime.Time并且我无法将这些属性保存到Mysql时间戳列中。

我能做什么?

Cos*_*age 27

要从time.Timetype 的 protobuf 字段获取 a google.protobuf.Timestamp,请使用在该类型上定义的AsTime方法timestamppb.Timestamp

在您的数据库或time.Time需要a 的任何其他位置生成插入调用时,调用myMsg.UpdateTime.AsTime()以获取所需的值(其中myMsg是相关 Protobuf 消息类型实例的变量)。


此答案假设您使用的是google.golang.org/protobuf包中定义的新 Protobuf APIv2 接口,或者您使用的是 APIv1 的 APIv2 兼容实现,在包github.com/golang/protobuf中定义的版本v1.20或更高版本。

许多项目仍要更新到这些版本。强烈建议您升级代码生成和工具链以从新功能中受益。

  • protobuf 可以在消息中定义属性 ``time.Time`` 类型吗? (2认同)
  • 简而言之,是的。protobuf 时间戳没有时区信息。时间到了。时间到了。因此,需要将 zoneinfo 添加到时间戳旁边的任何消息中。但是,由于 protobuf 主要与微服务一起使用且通常不面向用户,因此很可能不需要在微服务级别维护 zoneinfo。 (2认同)

ign*_*ite 6

AsTime方法可用于将 Timestamp 消息转换为标准 Go time.Time 值(UTC)

t := ts.AsTime()
... // make use of t as a time.Time
Run Code Online (Sandbox Code Playgroud)

AsTime 方法尽力执行转换。具有非正常值的时间戳(例如,超出 0 和 99999999 的纳秒)在转换为 time.Time 期间被标准化。要根据 timestamp.proto 中记录的限制手动检查无效时间戳,请另外调用 CheckValid 方法:

if err := ts.CheckValid(); err != nil {
    ... // handle error
}
Run Code Online (Sandbox Code Playgroud)

这记录在timestamppb包中。