Java Reference
In-Depth Information
calendar.roll(calendar.MONTH, false); // Go back a month
The change can affect other fields. If the original month was January, rolling it back by one will make
the date December of the previous year.
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 is a fairly fundamental requirement and you have three
methods available for comparing
Calendar
objects:
Method
Description
before()
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.
after()
Returns
true
if the current object corresponds to a time after that of
the
Calendar
object passed as an argument.
equals()
Returns true if the current object corresponds to a time that is identical
to that of the
Calendar
object passed as an argument.
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 will deduce important information about when you were born. It uses the
FormattedInput
class to get input from the keyboard, so copy the class to the directory containing
the source file for this example. Here's the code:
import java.util.GregorianCalendar;
import java.text.DateFormatSymbols;
class TryCalendar {