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

How to Convert Between Java 8 LocalDateTime and java.util.Date?

DDD
Release: 2024-11-19 19:57:02
Original
387 people have browsed it

How to Convert Between Java 8 LocalDateTime and java.util.Date?

Converting Between Java 8 LocalDateTime and java.util.Date

Converting from java.util.Date to LocalDateTime:

To convert a java.util.Date object to a LocalDateTime, first convert the Date to an Instant using its toInstant() method:

Date in = new Date();
Instant instant = in.toInstant();
Copy after login

Then create a LocalDateTime object using LocalDateTime.ofInstant(), specifying the desired time zone:

LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
Copy after login

Converting from LocalDateTime to java.util.Date:

To convert a LocalDateTime back to a java.util.Date, first convert it to an Instant using its atZone() and toInstant() methods:

LocalDateTime ldt = ...
ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
Instant instant = zdt.toInstant();
Copy after login

Finally, create a new java.util.Date object from the Instant:

Date out = Date.from(instant);
Copy after login

Considerations:

  • The conversion from LocalDateTime to ZonedDateTime may result in unexpected behavior due to Daylight Saving Time.
  • Round-tripping between java.util.Date and LocalDateTime may result in a different instant due to Daylight Saving Time.
  • java.time.* uses the ISO calendar system for all dates, while java.util.Date uses the Gregorian calendar after October 15, 1582, and the Julian calendar before that.

The above is the detailed content of How to Convert Between Java 8 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template