Java Reference
In-Depth Information
Seven hundred days from 2013-11-09 is 2015-10-10
Interfacing with Legacy Date and Calendar Classes
Problem
You need to deal with the old
Date
and
Calendar
classes.
Solution
Assuming you have code using the original
java.util.Date
and
java.util.Calendar
,
you can convert values as needed using conversion methods.
Discussion
All the classes and interfaces in the new API were chosen to avoid conflicting with the tradi-
tional API. It is thus possible, and will be common for a while, to have imports from both
packages into the same code.
To keep the new API clean, most of the necessary conversion routines were added
to the old
API
.
Table 6-7
summarizes these conversion routines; note that the methods are static if they
are shown being invoked with a capitalized class name, else they are instance methods.
Table 6-7. Legacy Date/Time interchange
Legacy Class
Convert to legacy
Convert to modern
java.util.Date
date.from(Instant)
Date.toInstant()
-
java.util.Calendar
calendar.toInstant()
java.util.GregorianCalendar GregorianCalendar.from(ZonedDateTime) calendar.toZonedDateTime()
-
java.util.TimeZone
timeZone.toZoneId()
java.time.DateTimeFormatter
-
dateTimeFormatter.toFormat()
The following code shows some of these APIs in action: