Converting java.util.Date to java.time.LocalDate
In Java 8 and later, the java.util.Date class has been superseded by the java.time.LocalDate class for representing dates. Therefore, it becomes necessary to convert Date objects to LocalDate objects.
Conversion Process
Obtain an Instant: Convert the Date object into an Instant using the toInstant() method.
Date input = new Date(); Instant instant = input.toInstant();
Specify a Time Zone: Since Date objects lack time zone information, choose a time zone. This can be the system default using ZoneId.systemDefault() or a custom one.
ZoneId zone = ZoneId.systemDefault();
Obtain a ZonedDateTime: Combine the Instant and the time zone to create a ZonedDateTime.
ZonedDateTime zdt = instant.atZone(zone);
Extract the LocalDate: Extract the local date from the ZonedDateTime using the toLocalDate() method.
LocalDate date = zdt.toLocalDate();
Java 9 and Later Optimization
Java 9 introduced a simplified method for this conversion:
LocalDate date = LocalDate.ofInstant(input.toInstant(), ZoneId.systemDefault());
Explanation
The above is the detailed content of How Do I Convert a java.util.Date to a java.time.LocalDate?. For more information, please follow other related articles on the PHP Chinese website!