Home > Java > javaTutorial > 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
Release: 2024-11-04 08:26:31
Original
376 people have browsed it

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>
Copy after login

From java.util.Calendar to Instant

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

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

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

From LocalTime to ZonedDateTime

Similarly, for LocalTime:

<code class="java">LocalTime localTime = zdt.toLocalTime();
ZonedDateTime zdt = ZonedDateTime.of(localDate, localTime, zoneId);</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template