Convert java.util.Date to java.time's Instant, OffsetDateTime, or ZonedDateTime
As we migrate towards the modern java.time framework, it's essential to know how to convert legacy java.util.Date objects into the appropriate java.time types. Here's a rundown of the equivalencies:
java.util.Date to Instant
Both represent a moment in UTC, so the conversion is straightforward:
Instant instant = myUtilDate.toInstant();
java.util.Date myUtilDate = java.util.Date.from(instant);
java.util.Date to java.time's OffsetDateTime or ZonedDateTime
Since these types incorporate time zone information, extracting the zone from the legacy Date is necessary:
// If the legacy date is a GregorianCalendar (which can hold time zone info)
if (myUtilCalendar instanceof GregorianCalendar) {
GregorianCalendar gregCal = (GregorianCalendar) myUtilCalendar;
ZonedDateTime zdt = gregCal.toZonedDateTime(); // ZonedDateTime with time zone
java.util.Calendar myUtilCalendar = java.util.GregorianCalendar.from(zdt);
}
Additional Conversion Mappings
Legacy Type | java.time Equivalent | Additional Notes |
---|---|---|
java.util.Calendar | Instant | Converts to the start of the day in UTC |
java.util.GregorianCalendar | ZonedDateTime | Retains time zone information |
java.util.LocalDate | ZonedDateTime | Requires a time zone to determine the date |
java.util.LocalTime | Instant | Converts to the start of the day in UTC |
java.util.LocalDateTime | ZonedDateTime | Requires a time zone to determine the date and time |
Important Considerations
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3