Conversion of java.util.Date to java.time.LocalDate
Problem:
How can you efficiently convert a java.util.Date object to the newer java.time.LocalDate format introduced in JDK 8/JSR-310?
Short Answer:
To achieve the conversion, use the following code:
Date input = new Date(); LocalDate date = input.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
Java 9 Solution:
A more efficient alternative has been added in Java SE 9:
Date input = new Date(); LocalDate date = LocalDate.ofInstant(input.toInstant(), ZoneId.systemDefault());
Explanation:
Unlike its name suggests, a java.util.Date object denotes an instant in time, rather than a specific date. To convert a java.util.Date to a compatible java.time.LocalDate, the following steps are necessary:
This conversion process accounts for the fact that a java.util.Date doesn't contain timezone information. Specifying the time zone enables the accurate conversion to a specific local date.
The above is the detailed content of How to Efficiently Convert java.util.Date to java.time.LocalDate?. For more information, please follow other related articles on the PHP Chinese website!