如何将字符串转换为 google.protobuf.Timestamp?

Saq*_*Ali 3 go protocol-buffers

我有一个 Go 字符串x := "2020-09-01T21:46:43Z"

这是我的 Protobuf3:

message MyMessage {
  google.protobuf.Timestamp mytimestamp = 1;
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能把这个字符串转换x成a google.protobuf.Timestamp

Mar*_*arc 5

使用ptypes包,它具有与 protobuf 类型相互转换的帮助程序。

可以帮助您的两个功能是:


ptypes.Timestamp:将 a 转换Timestamp为 a time.Time

func Timestamp(ts *timestamppb.Timestamp) (time.Time, error)
Run Code Online (Sandbox Code Playgroud)

调用 timestamppb.New 函数。这将 a 转换time.Time为 a Timestamp

func timestamppb.New(t time.Time) *timestamppb.Timestamp
Run Code Online (Sandbox Code Playgroud)

请注意,两者都处理time.Time,即标准库中的时间类型。您首先需要将字符串解析为time.Timeusing time.Parse


把它们放在一起我们有:

func Timestamp(ts *timestamppb.Timestamp) (time.Time, error)
Run Code Online (Sandbox Code Playgroud)