How to convert LocalDateTime to com.google.protobuf.Timestamp?
In general, no, your approach is not correct. The reason is that a LocalDateTime
does not have an associated timezone, so it is ambiguous by nature. To convert it to an actual timestamp (an absolute point in time, independent of timezones), you need to know what timezone it was measured in.
By calling localDateTime.toInstant(ZoneOffset.UTC)
, you are assuming that your localDateTime
was actually measured in the UTC timezone. Instead, you should be using the timezone that the LocalDateTime
is stored in. If you don't know, then your input data is inherently ambiguous and you'll need to fix that first.
Note that this has nothing to do with the fact that the Unix epoch is usually specified in UTC. We might as well say that the Unix epoch is 1970-01-01T08:00:00+08:00
, and it would be the same instant in time.
The rest of it seems correct to me.
Here's a routine that pulls together the comments from the question and actual answer to this question:
protected Timestamp convertLocalDateTimeToGoogleTimestamp(LocalDateTime localDateTime) {
Instant instant = localDateTime.toInstant(ZoneOffset.UTC);
Timestamp result = Timestamp.newBuilder()
.setSeconds(instant.getEpochSecond())
.setNanos(instant.getNano())
.build();
return result;
}