Java › Java Date & Time API (java.time)
How would you convert between the legacy java.util.Date/Calendar classes and the modern java.time API when working with older libraries or APIs that still require the legacy types?
AdvancedAnswer
The java.time API provides explicit conversion bridge methods specifically for interoperating with legacy code that hasn't been (or can't easily be) migrated: Date.from(Instant) and date.toInstant() convert between Date and Instant; GregorianCalendar.from(ZonedDateTime) and calendar.toZonedDateTime() convert between Calendar and ZonedDateTime -- these bridge methods let you isolate legacy-API interop to specific boundary points in a codebase (like a third-party library's method signature still requiring a Date parameter) while using the modern, safer java.time types throughout the rest of your own code, converting only at the necessary boundary rather than propagating legacy types more broadly than necessary.
// Modern code internally uses Instant
Instant modernInstant = Instant.now();
// Convert to legacy Date only at the boundary where a legacy API requires it
Date legacyDate = Date.from(modernInstant);
legacyLibraryMethod(legacyDate); // some older API that still requires java.util.Date
// Convert a legacy Date received FROM an old API back to modern Instant
Instant convertedBack = legacyDate.toInstant();Real-world example A codebase primarily using modern java.time types throughout still needs to call a third-party reporting library's API that only accepts java.util.Date parameters, using Date.from(instant) specifically at that narrow integration boundary while keeping the rest of the application's own code entirely on the safer, immutable java.time types.