Java Reference
In-Depth Information
Of course, having modified a GregorianCalendar object, you can get the current instant back as a Date
object using the getTime() method that we saw earlier. You can then use a DateFormat object to present
this in a readable form.
Comparing Calendars
Checking the relationship between dates represented by Calendar objects is a fairly fundamental require-
ment and you have four methods available for comparing them (shown in Table 15-3 ):
TABLE 15-3 : Methods for Comparing Calendar Objects
METHOD
DESCRIPTION
Returns true if the current object corresponds to a time before that of the Calendar object
passed as an argument. Note that this implies a true return can occur if the date is the same but
the time is different.
before()
Returns true if the current object corresponds to a time after that of the Calendar object passed
as an argument.
after()
Returns true if the current object corresponds to a time that is identical to that of the Calendar
object passed as an argument.
equals()
Returns a value of type int that is negative, zero, or positive depending on whether the time
value for the current object is less than, equal to, or greater than the time value for the argument.
compareTo(Calendar
c)
These are very simple to use. To determine whether the object thisDate defines a time that precedes the
time defined by the object today , you could write:
if(thisDate.before(today)) {
// Do something...
}
Alternatively you could write the same thing as:
if(today.after(thisDate)) {
// Do something...
}
It's time to look at how we can use calendars.
TRY IT OUT: Using a Calendar
This example deduces important information about when you were born. It uses the FormattedInput
class from Chapter 8 to get input from the keyboard, so copy this class and the source file for the Inval-
idUserInputException class to a new directory for the source files for this example. Here's the code:
import java.util.GregorianCalendar;
import java.text.DateFormatSymbols;
import static java.util.Calendar.*;
 
 
Search WWH ::




Custom Search