Dates and Times
Working with dates and times without the proper tools can be a
chore. Fortunately, Java has three classes that handle most of the work
for you. The java.util.Date class
encapsulates a point in time. The java.util.GregorianCalendar class, which extends
the abstract java.util.Calendar,
translates between a point in time and calendar fields like month, day,
and year. Finally, the java.text.DateFormat class knows how to generate
and parse string representations of dates and times in many
languages.[32]
The separation of the Date and
Calendar classes is analogous to having
a class representing temperature and a class that translates that
temperature to Celsius units. A Date
represents an absolute point in time as defined by a number of
milliseconds from the reference point: midnight, Jan 1, 1970, GMT. This is
the same frame of reference used by the System.currentTimeMillis() call. A Calendar encapsulates a point in time and maps
it to higher-level (and messier) notions like years, months, weeks, and
days, and deals with discontinuities like leap years. Conceivably, we
could define subclasses of Calendar
other than the default GregorianCalendar, say JulianCalendar or LunarCalendar, that map time using other
sociological or cultural conventions.[33]
Working with Calendars
The default GregorianCalendar constructor creates a
calendar initialized to the current time, in the current time
zone:
GregorianCalendarnow=newGregorianCalendar();
However, more generally we can just ...