Protobuf时间戳:使用Java 8时间.Instant

20

我正在使用protobuf,其中一个消息使用google.protobuf.Timestamp类型。

当生成Java代码时,生成的protobuf类使用com.google.protobuf.Timestamp

有没有办法告诉protobuf使用新的Java 8类型(例如time.Instant)? 我不想让类型转换在我使用protobuf的任何地方都变得混乱。最理想的情况是在生成的代码内部完成。

4个回答

34
Instant instant = Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos());

3
如果一小段代码的含义显而易见,对于正在寻找问题答案的用户来说很有帮助,那么省略无关紧要的内容以便突出重点是可以接受的。在这种情况下,点赞数就足以说明一切。 - TheOperator

12

java.time.Instant 转换为 com.google.protobuf.Timestamp

com.google.protobuf.Timestamp.newBuilder()
    .setSeconds(myInstant.getEpochSecond())
    .setNanos(myInstant.getNano());

com.google.protobuf.Timestamp 转换为 java.time.Instant

Instant.ofEpochSecond(myProtoTimestamp.getSeconds(), myProtoTimestamp.getNanos());

1
在这个问题中,我要求更改生成代码中使用的类型,以避免出现此段代码。 - maja

8
如果有人在使用Kotlin编写代码,可以像这样实现Louis的解答作为扩展函数:
fun Timestamp.toInstant(): Instant = Instant.ofEpochSecond(seconds, nanos.toLong())

然后你只需使用 myProto.myTimestampField.toInstant()


2
我不确定是否有一种选项可以按照您想要的方式生成,但更好的方法可能是在gRPC文档中查看此处: https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/util/Timestamps
然后选择最适合您的选项。例如:
Instant anInstant = Instant.ofEpochMilli(com.google.protobuf.util.Timestamps.toMillis(someGoogleProtobufTimestamp));

如果你正确导入(只显示示例中使用的软件包),它看起来会更短更好看。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接