【问题标题】:Parsing datetimestamps with timezone offset in Go using google.protobuf.Timestamp使用 google.protobuf.Timestamp 在 Go 中解析具有时区偏移的日期时间戳
【发布时间】:2019-08-03 23:59:42
【问题描述】:

我正在创建一个使用 GRPC 和 protobuf 的 Go 应用程序。我的 RPC 服务将接收包含 google.protobuf.Timestamp 类型的消息,对其进行解析并最终将其保存在数据库中或对其执行更多操作。

对于google.protobuf.Timestamp 类型的有效输入,我感到困惑。我希望对带有时区偏移的日期时间戳使用以下格式。

2019-02-15T13:00:00+01:00

这是我正在使用的 proto 文件。

syntax = "proto3"
package example;
import "google/protobuf/timestamp.proto"

service Tester {
 rpc ParseDateTimeStamp(TSRequest) returns (TSReply) {}
}

message TSRequest {
  google.protobuf.Timestamp dts = 1;
}

message TSReply {
 string message = 1;
}

问题是当我向 GRPC 服务器发送包含日期时间戳的消息时。我希望给定的2019-02-15T13:00:00+01:00 datetimestamp 的类型*tsbp.Timestamp 是有效的,并给我从纪元开始的适当秒数。 (从 timestamp.go 调用 GetSeconds() 之后)

对于上面的示例输入,调用 ptypes.TimestampString(ts *tspb.Timestamp) 返回 1970-01-01T00:00:00Z

google.protobuf.Timestamp 是否接受带有 +- 偏移量的日期时间戳?

或者我是否必须将输入输入为 String 类型,然后使用 time.Format 解析为 time.Time 而不是在 protobuf 中使用时间戳变量类型?如果是这样,你能提供一个例子吗?

【问题讨论】:

  • 在返回TSReply 消息时 - 您是否希望它包含原始时区偏移量?如果是这样,您的输入值ptype.Timestamp 没有存储 TZ 值,因此任何偏移量都需要包含在额外的字段中。

标签: go protocol-buffers grpc-go


【解决方案1】:

google.protobuf.Timestamp 的 gRPC 消息类型在内部只有两个 int64

message Timestamp {
  // Represents seconds of UTC time since Unix epoch
  // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
  // 9999-12-31T23:59:59Z inclusive.
  int64 seconds = 1;

  // Non-negative fractions of a second at nanosecond resolution. Negative
  // second values with fractions must still have non-negative nanos values
  // that count forward in time. Must be from 0 to 999,999,999
  // inclusive.
  int32 nanos = 2;
}

所以在这种格式类型中,没有什么可以解析

通常需要:

  • 一种类似于2019-02-15T13:00:00+01:00 的字符串格式,并使用time.Parse 转换为time.Time
  • 然后使用ptypes.TimestampProto()time.Time 转换为*tspb.Timestamp

仅供参考,在您引用的输出中,您会看到 zero 时间戳(即秒和纳秒都为零) - 因此是 "1970-01-01T00:00:00Z" 输出。


实现上述流程:

ts, err := time.Parse(time.RFC3339, "2019-02-15T13:00:00+01:00")

pbts, err := ptypes.TimestampProto(ts) // ptypes.Timestamp:"seconds:1550232000 "

fmt.Println(ptypes.TimestampString(pbts)) // "2019-02-15T12:00:00Z"

Playground

注意: ptype.Timestamp 被剥夺任何时区 - Z 所以 UTC 时间。因此,如果您需要保留 time.Time 的时区,除了您的 google.protobuf.Timestamp 消息之外,还需要在您的 gRPC 消息中发送偏移量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2016-10-29
    • 2021-02-16
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    相关资源
    最近更新 更多