我该如何获取时间。Golangprotobuf v3结构中的时间

时间:2018-10-14 12:14:03

标签: mysql go timestamp protocol-buffers

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

google.protobuf.Timestamp UpdateTime = 9;

但是经过协议编译后,UpdateTime属性成为golang结构中的指针*timestamp.Timestamp,它不是time.Time,而且我无法将这些属性保存到Mysql timestamp列中。

我该怎么办?

2 个答案:

答案 0 :(得分:2)

AsTime 方法可用于将 Timestamp 消息转换为标准的 Go 时间。UTC 中的时间值:

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

AsTime 方法会尽最大努力执行转换。具有非规范值的时间戳(例如,超过 0 和 99999999 的纳秒,包括这两个值)在转换为 time.Time 期间被规范化。要根据 timestamp.proto 中记录的限制手动检查无效的时间戳,请另外调用 CheckValid 方法:

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

这记录在 timestamppb 包中。

答案 1 :(得分:0)

要从time.Time类型的protobuf字段中获取google.protobuf.Timestamp,请使用ptypes.Timestamp helper function

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