Convert java.util.Date to what “java.time” type?
Explanation:
The java.time framework provides modern and improved date and time classes compared to the legacy java.util classes. This framework offers more flexibility, precision, and functionality. When working with legacy code that still uses java.util types, it's necessary to be able to convert between the two frameworks.
Conversion Options:
1. From java.util.Date to java.time.Instant:
To convert from java.util.Date, use the .toInstant() method on the Date object:
<code class="java">Instant instant = myUtilDate.toInstant();</code>
2. From java.util.Calendar to Instant:
To convert from Calendar, use the .toInstant() method:
<code class="java">Instant instant = myUtilCalendar.toInstant() ;</code>
3. From java.util.GregorianCalendar to ZonedDateTime:
To convert, downcast Calendar to GregorianCalendar and use the .toZonedDateTime() method to obtain a ZonedDateTime:
<code class="java">if (myUtilCalendar instanceof GregorianCalendar) { GregorianCalendar gregCal = (GregorianCalendar) myUtilCalendar; ZonedDateTime zdt = gregCal.toZonedDateTime(); }</code>
4. From Instant to Other java.time Types:
Conversions from java.time Types to java.util.Date:
To convert from Instant to Date, extract the Instant and then apply .toInstant() on the Date:
<code class="java">java.util.Date myUtilDate = java.util.Date.from(instant);</code>
Note:
When converting from java.time types to java.util types, precision may be lost because java.util.Date and java.util.Calendar only handle milliseconds while java.time types have nanosecond precision.
The above is the detailed content of How to Convert `java.util.Date` to `java.time` Types?. For more information, please follow other related articles on the PHP Chinese website!