THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

Note that this is not localized output. No matter what the default locale, the date will be in this format,
adjusted for the current time zone.


You can compare two dates with the before and after methods, which return TRue if the object on which
they are invoked is before or after the other date. Or you can compare the long values you get from invoking
getTime on the two objects. The method setTime lets you change the time to a different long.


The Date class provides no support for localization and has effectively been replaced by the more
sophisticated and locale-sensitive Calendar and DateFormat classes.


24.4.1. Calendars


Calendars mark the passage of time. Most of the world uses the same calendar, commonly called the
Gregorian calendar after Pope Gregory XIII, under whose auspices it was first instituted. Many other
calendars exist in the world, and the calendar abstractions are designed to express such variations. A given
moment in time is expressed as a date according to a particular calendar, and the same moment can be
expressed as different dates by different calendars. The calendar abstraction is couched in the following form:



  • An abstract Calendar class that represents various ways of marking time
    An abstract TimeZone class that represents time zone offsets and other adjustments, such as daylight
    saving time



An abstract java.text.DateFormat class that defines how one can format and parse date and
time strings


Because the Gregorian calendar is commonly used, you also have the following concrete implementations of
the abstractions:



  • A GregorianCalendar class

  • A SimpleTimeZone class for use with GregorianCalendar

  • A java.text.SimpleDateFormat class that formats and parses Gregorian dates and times


For example, the following code creates a GregorianCalendar object representing midnight (00:00:00),
October 26, 1972, in the local time zone, then prints its value:


Calendar cal =
new GregorianCalendar(1972, Calendar.OCTOBER, 26);
System.out.println(cal.getTime());


The method getTime returns a Date object for the calendar object's time, which was set by converting a
year, month, and date into a millisecond-measured long. The output would be something like this
(depending on your local time zone of course):


Thu Oct 26 00:00:00 GMT+10:00 1972


You can also work directly with the millisecond time value by using getTimeInMillis and
setTimeInMillis. These are equivalent to working with a Date object; for example,
getTimeInMillis is equivalent to invoking getTime().getTime().


The abstract Calendar class provides a large set of constants that are useful in many calendars, such as
Calendar.AM and Calendar.PM for calendars that use 12-hour clocks. Some constants are useful only

Free download pdf