doushi3202 2018-08-30 02:05
浏览 564
已采纳

如何在Go的时间库中使用Protobuf的时间戳库

Import from github.com/golang/protobuf/ptypes/timestamp gives a native timestamp implementation by Protobuf, could be used inside of your protobuf definitions to represent time. A closer look at the timestamp.pb.go file provided looks like it generated some struct like this:

type Timestamp struct {
    Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"`
    Nanos                int32    `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"`
    XXX_NoUnkeyedLiteral struct{} `json:"-"`
    XXX_unrecognized     []byte   `json:"-"`
    XXX_sizecache        int32    `json:"-"`
}

There are some commented examples inside the timestamp.pb.go but I'm not understanding it very well.

To use it in relation with go's time library. I'm not sure how I'm suppose to set the fields inside of Timestamp. I assuming "conversion" between the two types aren't difficult, but I'm quit new to Go and protobuf. Any help would be appreciated.

  • 写回答

1条回答 默认 最新

  • dongyan8929 2018-08-30 05:18
    关注

    You have to convert this manually into time.Time.

    For non-pointer values:

    if !u.Timestamp.IsZero() {
        timestamp, _ := ptypes.TimestampProto(u.Timestamp)
        up.Timestamp = timestamp
    }
    

    For pointer values:

    if u.Timestamp != nil {
        timestamp, _ := ptypes.TimestampProto(*u.Timestamp)
        up.Timestamp = timestamp
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错