在使用protobuf定义rpc接口实现异构语言调用时,碰到protobuf不支持Java的LocalDateTime,手动进行转换
使用偏移转换ZoneOffset.UTC
Instant instant = time.toInstant(ZoneOffset.UTC);
return Timestamp.newBuilder()
.setSeconds(instant.getEpochSecond())
.setNanos(instant.getNano())
.build();
使用时区转换ZoneId
Instant instant = time.atZone(ZoneId.systemDefault()).toInstant();
return Timestamp.newBuilder()
.setSeconds(instant.getEpochSecond())
.setNanos(instant.getNano())
.build();
LocalDateTime表示没有时区的日期时间,如2019-10-25T12:15:30,而Instant是时间线上的一个瞬时点。
我们可以通过以下方式在Java LocalDateTime和Instant之间进行转换。
- 使用LocalDateTime.toInstant()方法将LocalDateTime转换为Instant。
Instant instant = localDateTime.toInstant(ZoneOffset.UTC);
- 使用LocalDateTime.ofInstant()方法将Instant转换成LocalDateTime。
LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault());