Java provides interoperability between the legacy classes and the new Date-Time API.
New methods have been added to the legacy classes to convert their objects to the new Date-Time classes and vice versa.
The following table contains the list of legacy datetime classes and their new Date-Time counterparts.
All legacy classes, except the Calendar class, provides two-way conversion.
The toXxx() methods are instance methods which return an object of the new datetime class.
The other methods are static methods, which accept an object of the new datetime class and return an object of the legacy class.
from() method in the java.util.Date class is a static method, which takes an Instant argument and returns a java.util.Date.
toInstant() method is an instance method and converts a java.util.Date into an Instant.
Legacy Class | New Methods in Legacy Class | Equivalent New Datetime Class |
---|---|---|
java.util.Date | from(), toInstant() | Instant |
Calendar | toInstant() | None |
GregorianCalendar | from(), toZonedDateTime() | ZonedDateTime |
TimeZone | getTimeZone(), toZoneId() | ZoneId |
java.sql.Date | valueOf(), toLocalDate() | LocalDate |
Time | valueOf(), toLocalTime() | LocalTime |
Timestamp | from(), toInstant() | Instant |
valueOf(), toLocalDateTime() | LocalDateTime | |
FileTime | from(), toInstant() | Instant |
The following code shows how to convert a Date to an Instant and vice versa.
import java.time.Instant; import java.util.Date; public class Main { public static void main(String[] args) { // Get the current date Date dt = new Date(); System.out.println("Date: " + dt); // Convert the Date to an Instant Instant in = dt.toInstant();/*from ww w . j a v a 2 s . c o m*/ System.out.println("Instant: " + in); // Convert the Instant back to a Date Date dt2 = Date.from(in); System.out.println("Date: " + dt2); } }