Google protocol buffers (3.0.0-beta2) offers the well-known type Timestamp.
The documentation describes the initialization in Java using System.currentTimeMillis() as following:
long millis = System.currentTimeMillis(); Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) .setNanos((int) ((millis % 1000) * 1000000)).build();
Is there an alternative way in the recent Java 8?
Advertisement
Answer
Starting with Java 8, there is the new Date/Time-API which makes this more appealing to the reader using java.time.Instant
Instant time = Instant.now(); Timestamp timestamp = Timestamp.newBuilder().setSeconds(time.getEpochSecond()) .setNanos(time.getNano()).build();
The result should be the same concerning precision.