Question: How do I convert java.util.Date or java.util.Calendar objects to the appropriate java.time framework types?
Answer:
To convert a java.util.Date to an Instant, use the toInstant method:
<code class="java">Instant instant = myUtilDate.toInstant();</code>
For java.util.Calendar objects, use the toInstant method:
<code class="java">Instant instant = myUtilCalendar.toInstant();</code>
To convert a java.util.GregorianCalendar to a ZonedDateTime, use the toZonedDateTime method:
<code class="java">if (myUtilCalendar instanceof GregorianCalendar) { GregorianCalendar gregCal = (GregorianCalendar) myUtilCalendar; ZonedDateTime zdt = gregCal.toZonedDateTime(); }</code>
Extract an Instant from the OffsetDateTime and use it to create a java.util.Date:
<code class="java">java.util.Date myUtilDate = java.util.Date.from(odt.toInstant());</code>
Similarly, extract an Instant from the ZonedDateTime:
<code class="java">java.util.Date myUtilDate = java.util.Date.from(zdt.toInstant());</code>
Convert a ZonedDateTime to a GregorianCalendar using the from method:
<code class="java">java.util.Calendar myUtilCalendar = java.util.GregorianCalendar.from(zdt);</code>
Going from a LocalDate to a ZonedDateTime requires specifying a time zone:
<code class="java">LocalDate localDate = zdt.toLocalDate(); ZonedDateTime zdt = localDate.atStartOfDay(zoneId);</code>
Similarly, for LocalTime:
<code class="java">LocalTime localTime = zdt.toLocalTime(); ZonedDateTime zdt = ZonedDateTime.of(localDate, localTime, zoneId);</code>
The above is the detailed content of How to Convert Between java.util.Date and java.time Types?. For more information, please follow other related articles on the PHP Chinese website!