"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How do I convert java.util.Date to java.time\'s Instant, OffsetDateTime, or ZonedDateTime?

How do I convert java.util.Date to java.time\'s Instant, OffsetDateTime, or ZonedDateTime?

Published on 2024-11-06
Browse:736

How do I convert java.util.Date to java.time\'s Instant, OffsetDateTime, or ZonedDateTime?

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:

Instant instant = myUtilDate.toInstant();

java.util.Date myUtilDate = java.util.Date.from(instant);

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:

// 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);
}

Additional Conversion Mappings

Legacy Typejava.time EquivalentAdditional Notes
java.util.CalendarInstantConverts to the start of the day in UTC
java.util.GregorianCalendarZonedDateTimeRetains time zone information
java.util.LocalDateZonedDateTimeRequires a time zone to determine the date
java.util.LocalTimeInstantConverts to the start of the day in UTC
java.util.LocalDateTimeZonedDateTimeRequires a time zone to determine the date and time

Important Considerations

  • Converting from a java.util.Date to a java.time type may result in loss of precision as nanosecond resolution is not supported by the legacy classes.
  • When converting to OffsetDateTime or ZonedDateTime, the time zone information must be preserved to ensure correct interpretation.
  • It's highly recommended to use java.time types in new code for enhanced precision and consistency.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3