Home >Java >javaTutorial >How to Convert Between java.time.LocalDateTime and java.util.Date?
With Java 8's introduction of the java.time package, developers have embraced its new API for handling date and time. Among its classes, LocalDateTime holds a timezone-independent date-with-time value.
However, legacy code often relies on the java.util.Date class. When integrating old and new codebases, converting between these two classes becomes necessary.
Conversion Approach:
From java.util.Date to LocalDateTime:
Code:
Date in = new Date(); LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
From LocalDateTime to java.util.Date:
Code:
LocalDateTime ldt = ... ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault()); Date output = Date.from(zdt.toInstant());
Note on Daylight Saving Time (DST):
Converting from LocalDateTime to java.util.Date via ZonedDateTime can introduce unexpected behavior due to DST. Certain LocalDateTime values may not exist or may occur twice during DST transitions. Refer to the Javadoc for atZone(ZoneId) for details.
Additional Considerations:
The above is the detailed content of How to Convert Between java.time.LocalDateTime and java.util.Date?. For more information, please follow other related articles on the PHP Chinese website!