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();
Then create a LocalDateTime object using LocalDateTime.ofInstant(), specifying the desired time zone:
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
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();
Finally, create a new java.util.Date object from the Instant:
Date out = Date.from(instant);
Considerations:
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!