[英]How to initialize Google protocol buffers Timestamp in Java?
Google protocol buffers (3.0.0-beta2) 提供了眾所周知的 Timestamp 類型。
該文檔描述了使用System.currentTimeMillis()在 Java中的初始化如下:
long millis = System.currentTimeMillis();
Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
.setNanos((int) ((millis % 1000) * 1000000)).build();
最近的Java 8 中是否有替代方法?
從Java 8開始,有新的Date/Time-API使用java.time.Instant使這對讀者更具吸引力
Instant time = Instant.now();
Timestamp timestamp = Timestamp.newBuilder().setSeconds(time.getEpochSecond())
.setNanos(time.getNano()).build();
結果應該與精度相同。
這些天,您可以使用:
import static com.google.protobuf.util.Timestamps.fromMillis;
import static java.lang.System.currentTimeMillis;
import com.google.protobuf.Timestamp;
...
Timestamp timestamp = fromMillis(currentTimeMillis());
請參閱以下位置的文檔:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.