[英]How to initialize Google protocol buffers Timestamp in Java?
Google protocol buffers (3.0.0-beta2) offers the well-known type Timestamp . Google protocol buffers (3.0.0-beta2) 提供了众所周知的 Timestamp 类型。
The documentation describes the initialization in Java using System.currentTimeMillis() as following:该文档描述了使用System.currentTimeMillis()在 Java中的初始化如下:
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 ?最近的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从Java 8开始,有新的Date/Time-API使用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:请参阅以下位置的文档:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.