Home >Java >javaTutorial >How to Convert `java.util.Date` to `java.time.LocalDate`?

How to Convert `java.util.Date` to `java.time.LocalDate`?

Linda Hamilton
Linda HamiltonOriginal
2024-12-08 02:49:10809browse

How to Convert `java.util.Date` to `java.time.LocalDate`?

Converting java.util.Date to java.time.LocalDate

Java's date and time API was overhauled in JDK 8/JSR-310, introducing a new paradigm for handling date-related operations. A common task in this transition is converting existing java.util.Date objects to the new java.time.LocalDate format.

Short Answer

To convert a java.util.Date to LocalDate, follow these steps:

Date input = new Date();
LocalDate date = input.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

Explanation

java.util.Date represents an instant in time without any time zone information. However, LocalDate represents a specific calendar date without time or time zone.

To convert a Date to LocalDate, you must first convert Date to Instant using the toInstant() method. An Instant has no time zone associated with it.

Next, you need to apply a time zone to the Instant to get a ZonedDateTime object. You can use ZoneId.systemDefault() to get the default system time zone.

Finally, you can extract the LocalDate component from the ZonedDateTime object using the toLocalDate() method.

Java 9 Answer

Java SE 9 introduced a simpler alternative to the above conversion:

Date input = new Date();
LocalDate date = LocalDate.ofInstant(input.toInstant(), ZoneId.systemDefault());

This method directly converts the Date to a LocalDate without the need for an intermediate ZonedDateTime object.

The above is the detailed content of How to Convert `java.util.Date` to `java.time.LocalDate`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn