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 = 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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.