如何在 Java 中初始化 Google 协议缓冲区时间戳?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36711835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:48:09  来源:igfitidea点击:

How to initialize Google protocol buffers Timestamp in Java?

javatimestampprotocol-buffers

提问by l00tr

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 Javausing 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 wayin the recent Java 8?

最近的Java 8 中是否有替代方法

回答by l00tr

Starting with Java 8, there is the new Date/Time-APIwhich 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.

关于精度,结果应该是相同的。

回答by Isaac Sheff

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:

请参阅以下位置的文档: