Home > Java > javaTutorial > How to Convert Between java.time.LocalDateTime and java.util.Date?

How to Convert Between java.time.LocalDateTime and java.util.Date?

Linda Hamilton
Release: 2024-11-13 02:53:02
Original
258 people have browsed it

How to Convert Between java.time.LocalDateTime and java.util.Date?

Converting 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:

  1. Convert the java.util.Date to an Instant using the toInstant() method.
  2. Specify a time zone using ZoneId.systemDefault() to create a LocalDateTime via ofInstant().

Code:

Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Copy after login

From LocalDateTime to java.util.Date:

  1. Use atZone(ZoneId) to convert LocalDateTime to a ZonedDateTime.
  2. Convert the ZonedDateTime to an Instant using toInstant(), then to a java.util.Date using Date.from().

Code:

LocalDateTime ldt = ...
ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
Date output = Date.from(zdt.toInstant());
Copy after login

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:

  • java.util.Date represents an instant on the time-line, while Instant in java.time.* represents an instant without a time zone.
  • Converting between LocalDateTime and java.util.Date may result in different instants due to discrepancies in calendar systems (Julian vs. Gregorian) before 1582.

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!

source:php.cn
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