How to initialize Google protocol buffers Timestamp in Java?
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.
These days, you can use:
import static com.google.protobuf.util.Timestamps.fromMillis;
import static java.lang.System.currentTimeMillis;
import com.google.protobuf.Timestamp;
...
Timestamp timestamp = fromMillis(currentTimeMillis());
See documentation at:
- https://docs.oracle.com/javase/10/docs/api/java/lang/System.html#currentTimeMillis()
- https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/util/Timestamps#fromMillis-long-