Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing Dates with Protocol Buffers

So after some searching, its been suggested to use an int64 epoch.

This is all well and great, but when interacting with my model, I would like to interact with actual LocalDate objects, so what are strategies for handling this?

The two strategies I can think of are:

  • transform the deserialized model into ANOTHER different model. This is creating an extra object, I was hoping to avoid this.
  • edit the generated models. I can't find any documentation on this so its probably quite risky

What is the common practice here?

like image 874
Cheetah Avatar asked Mar 30 '15 14:03

Cheetah


1 Answers

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();
}
like image 98
Cheetah Avatar answered Oct 12 '22 14:10

Cheetah