乐闻世界logo
搜索文章和话题

How to convert Google proto timestamp to Java LocalDate?

1个答案

1

In Java, converting Google Protobuf timestamps to LocalDate objects can be achieved by using the Instant and LocalDate classes from the java.time package. Below are the specific steps and examples:

  1. Adding Dependencies (if using Maven): To use Google Protobuf, add the Protobuf dependency to your project's pom.xml file.
xml
<dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>3.12.0</version> </dependency>
  1. Obtaining the Protobuf Timestamp: Assume you have received a Protobuf Timestamp object from a data source or API.

  2. Conversion Process: First, convert the Protobuf Timestamp to a Java Instant object, then convert the Instant to a LocalDate.

Below is a specific code example:

java
import com.google.protobuf.Timestamp; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; public class TimestampToLocalDate { public static LocalDate convert(Timestamp timestamp) { // Convert the Timestamp to an Instant Instant instant = Instant.ofEpochSecond( timestamp.getSeconds(), timestamp.getNanos() ); // Convert the Instant to a LocalDate // Using the system default time zone; you can specify a time zone, e.g., ZoneId.of("Asia/Shanghai") LocalDate date = instant.atZone(ZoneId.systemDefault()).toLocalDate(); return date; } public static void main(String[] args) { // Create a Timestamp instance (assuming current time) Timestamp timestamp = Timestamp.newBuilder() .setSeconds(System.currentTimeMillis() / 1000) .setNanos(0) .build(); LocalDate localDate = convert(timestamp); System.out.println("LocalDate: " + localDate); } }

In the above code, the Instant.ofEpochSecond method is used to convert the seconds and nanoseconds of the Timestamp to an Instant object. Then, the Instant.atZone method is used to convert the Instant to a ZonedDateTime, and finally, toLocalDate is called to obtain the LocalDate object.

This conversion is very useful when dealing with scenarios that require only the date and not the time, such as birthdays or anniversaries.

2024年7月24日 01:08 回复

你的答案