Skip to content

How to initialize Google protocol buffers Timestamp in Java?

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?



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 =;
Timestamp timestamp = Timestamp.newBuilder().setSeconds(time.getEpochSecond())

The result should be the same concerning precision.

User contributions licensed under: CC BY-SA
9 People found this is helpful