Golang:如何转换时间.时间到Protobuf时间戳?

ktca8awb  于 2023-09-28  发布在  Go
关注(0)|答案(2)|浏览(209)

我有一个时间。Golang 10-30 00:49:07.1236中的时间变量需要转换为Go Protobuf timestamp.Timestamp。有什么想法可以用来实现这一点?还是我看问题的Angular 不对

idfiyjo8

idfiyjo81#

参见timestamppb中的NewTimestamp.AsTime
支持time.TimeTimestamp之间的转换

vcudknz3

vcudknz32#

下面的代码将给予转换时间。时间到protobuf timestamppb格式

import "google.golang.org/protobuf/types/known/timestamppb"
timeNow := time.Now()
timestamp := timestamppb.Timestamp{
    Seconds: timeNow.Unix(),
    Nanos:   int32(timeNow.Nanosecond()),
}
fmt.Printf("as timestamp %+v\n", timestamp)
fmt.Printf("as time.Time %+v\n", timestamp.AsTime().Local())

输出如下所示:

as timestamp {state:{NoUnkeyedLiterals:{} DoNotCompare:[] DoNotCopy:[] atomicMessageInfo:<nil>} sizeCache:0 unknownFields:[] Seconds:1694773177 Nanos:777135000}
as time.Time 2023-09-15 15:49:37.777135 +0530 IST

相关问题