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
Release: 2024-12-08 02:49:10
Original
764 people have browsed it

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();
Copy after login

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());
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template