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:
<code class="java">Instant instant = myUtilDate.toInstant(); java.util.Date myUtilDate = java.util.Date.from(instant);</code>
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:
<code class="java">// 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); }</code>
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
The above is the detailed content of How do I convert java.util.Date to java.time\'s Instant, OffsetDateTime, or ZonedDateTime?. For more information, please follow other related articles on the PHP Chinese website!