I'm using protobuf, and one of my message uses the google.protobuf.Timestamp
type.
When generating the Java-Code, the resulting protobuf classes use com.google.protobuf.Timestamp
.
Is there a way to tell protobuf to use the new Java 8 types (e.g. time.Instant
) instead? I don't want the type conversion clutter my code, everywhere I use protobuf. Ideally, it is done inside the generated code itself.
Instant instant = Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos());
If anyone's writing in Kotlin, Louis' answer can be implemented as an extension function like this:
fun Timestamp.toInstant(): Instant = Instant.ofEpochSecond(seconds, nanos.toLong())
Then you can just do myProto.myTimestampField.toInstant()
Not sure about an option for making the generation generate it as you want it, but may be a better approach would be to check at the gRPC documentation here:
https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/util/Timestamps
And pick the best one that suits for you. For example:
Instant anInstant = Instant.ofEpochMilli(com.google.protobuf.util.Timestamps.toMillis(someGoogleProtobufTimestamp));
Would look a lot shorter and nice once you import properly (just showing the packages used in the example)
java.time.Instant
to com.google.protobuf.Timestamp
:com.google.protobuf.Timestamp.newBuilder()
.setSeconds(myInstant.getEpochSecond())
.setNanos(myInstant.getNano());
com.google.protobuf.Timestamp
to java.time.Instant
:Instant.ofEpochSecond(myProtoTimestamp.getSeconds(), myProtoTimestamp.getNanos());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With