Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

protobuf timestamp: Use Java 8 time.Instant

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.

like image 637
maja Avatar asked Jan 19 '18 15:01

maja


4 Answers

Instant instant = Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos());
like image 87
Louis Thibault Avatar answered Oct 19 '22 17:10

Louis Thibault


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()

like image 40
Rik Avatar answered Oct 19 '22 19:10

Rik


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)

like image 25
user1228603 Avatar answered Oct 19 '22 17:10

user1228603


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());
like image 4
Jay Avatar answered Oct 19 '22 18:10

Jay