Dates
Working
with dates and times without the proper tools can be a
chore.[32]
In
SDK 1.1 and later, you get three classes that do all the hard work
for you. The java.util.Date class encapsulates a
point in time. The
java.util.GregorianCalendar
class, which descends from 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.[33]
The separation of the Date class and the
GregorianCalendar class is analogous to having a
class representing temperature and a class that translates that
temperature to Celsius units. Conceivably, we could define other
subclasses of Calendar, say
JulianCalendar or
LunarCalendar.
The default GregorianCalendar
constructor
creates an object that represents the
current time, as determined by the system clock:
GregorianCalendar now = new GregorianCalendar( );
Other constructors accept values to specify the point in time. In the first statement in the following code, we construct an object representing August 9, 1996; the second statement specifies both a date and a time, yielding an object that represents 9:01 a.m., April 8, 1997.
GregorianCalendar daphne =
new GregorianCalendar(1996, Calendar.AUGUST, 9);
GregorianCalendar sometime =
new GregorianCalendar(1997, Calendar.APRIL, 8, 9, 1); // 9:01 AMWe can also create a GregorianCalendar by setting
specific fields using
the
set( )
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access