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

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-13 02:53:02211browse

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());

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());

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!

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