Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize Google protocol buffers Timestamp in Java?

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?

like image 584
AntiTiming Avatar asked Apr 19 '16 07:04

AntiTiming


People also ask

What is protobuf timestamp?

Reference documentation and code samples for the Kubernetes Engine V1 API class Google::Protobuf::Timestamp. A Timestamp represents a point in time independent of any time zone or local calendar, encoded as a count of seconds and fractions of seconds at nanosecond resolution.

How do I set default value in protobuf?

For bool s, the default value is false. For numeric types, the default value is zero. For enums , the default value is the first value listed in the enum's type definition. This means care must be taken when adding a value to the beginning of an enum value list.

Is Google protobuf timestamp Nullable?

Protobuf messages are either present (possibly default) valued or optional but they can't be null.

How do I create a Java proto file?

The protocol buffer compiler produces Java output when invoked with the --java_out= command-line flag. The parameter to the --java_out= option is the directory where you want the compiler to write your Java output. For each . proto file input, the compiler creates a wrapper .


1 Answers

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.

like image 188
AntiTiming Avatar answered Sep 21 '22 08:09

AntiTiming