Home  >  Article  >  Java  >  How to Convert Between java.util.Date and java.time Types?

How to Convert Between java.util.Date and java.time Types?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-04 08:26:31351browse

How to Convert Between java.util.Date and java.time Types?

How to Convert java.util.Date to java.time Types

Question: How do I convert java.util.Date or java.util.Calendar objects to the appropriate java.time framework types?

Answer:

From java.util.Date to Instant

To convert a java.util.Date to an Instant, use the toInstant method:

<code class="java">Instant instant = myUtilDate.toInstant();</code>

From java.util.Calendar to Instant

For java.util.Calendar objects, use the toInstant method:

<code class="java">Instant instant = myUtilCalendar.toInstant();</code>

From java.util.GregorianCalendar to ZonedDateTime

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>

From OffsetDateTime to java.util.Date

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>

From ZonedDateTime to java.util.Date

Similarly, extract an Instant from the ZonedDateTime:

<code class="java">java.util.Date myUtilDate = java.util.Date.from(zdt.toInstant());</code>

From ZonedDateTime to GregorianCalendar

Convert a ZonedDateTime to a GregorianCalendar using the from method:

<code class="java">java.util.Calendar myUtilCalendar = java.util.GregorianCalendar.from(zdt);</code>

From LocalDate to ZonedDateTime

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>

From LocalTime to ZonedDateTime

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!

Statement:
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