Serializing Dates with Protocol Buffers
I went with creating a generic solution for all dates/times:
message Timestamp {
int64 seconds = 1;
int32 nanos = 2;
}
With the following converters:
public static Timestamp fromLocalDate(LocalDate localDate) {
Instant instant = localDate.atStartOfDay().toInstant(ZoneOffset.UTC);
return Timestamp.newBuilder()
.setSeconds(instant.getEpochSecond())
.setNanos(instant.getNano())
.build();
}
public static LocalDate toLocalDate(Timestamp timestamp) {
return LocalDateTime.ofInstant(Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos()), ZoneId.of("UTC"))
.toLocalDate();
}
There is no need to create your own version of Timestamp.
You can simply use google.protobuf.Timestamp
(source):
import "google/protobuf/timestamp.proto";
message Application {
google.protobuf.Timestamp date = 1;
}
It's the standard (proto) way to create Date
objects.
It's easy to convert an Instant
into a google.Timestamp
with the new Java8 time API
LocalDate date = ...;
final Instant instant = java.sql.Timestamp.valueOf(date.atStartOfDay()).toInstant();
Timestamp t = Timestamp.newBuilder().setSeconds(instant.getEpochSecond()).build();
Please note that Google protobuf lib contains an helper for Timestamp
:
https://github.com/google/protobuf/blob/master/java/util/src/main/java/com/google/protobuf/util/Timestamps.java