Java Reference
In-Depth Information
To obtain a reference to a
TimeZone
object corresponding to a given time zone ID, you pass the ID to
the static
getTimeZone()
method. For instance, we could create a
Calendar
object for the Chicago
time zone like this:
GregorianCalendar calendar =
new GregorianCalendar(TimeZone.getTimeZone("America/Chicago"));
If you want to know what all the time zones IDs are, you could list them like this:
String[] ids = TimeZone.getAvailableIDs();
for(int i = 0 ; i<ids.length ; i++)
System.out.println(ids[i]);
The calendar created from a
TimeZone
object will have the default locale. If you want to specify the locale
explicitly, there's a constructor that accepts a
Locale
reference as the second argument. For example:
GregorianCalendar calendar =
new GregorianCalendar(TimeZone.getTimeZone("America/Chicago"). Locale.US);
You can also create a
Calendar
object from a locale:
GregorianCalendar calendar =
new GregorianCalendar(Locale.UK);
This will create a calendar set to the current time in the default time zone within the UK.
Setting the Date and Time
If you have a
Date
object available, there is a
setTime()
method that you can pass a
Date
object, to
set a
GregorianCalendar
object to the time specified by the
Date
object:
calendar.setTime(date);
More typically you will want to set the date and/or time with explicit values such as day, month, and
year, and there are several overloaded versions of the
set()
method for setting various components of
the date and time. These are inherited in the
GregorianCalendar
class from its superclass, the
Calendar
class. You can set a
GregorianCalendar
object to a particular date like this:
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(1995, 10, 29); // Date set to 29th November 1999
The three arguments to the
set()
method here are the year, the month, and the day as type
int
. You need
to take care with this method as it's easy to forget that the month is zero-based with January specified by 0.
Note that the fields reflecting the time setting within the day will not be changed. They will remain at
whatever they were. You can reset all fields for a
GregorianCalendar
object to zero by calling its
clear()
method, so calling
clear()
before you call
set()
here would ensure the time fields are all zero.