Java Reference
In-Depth Information
"Pacific/Guam" "Antarctica/Palmer"
"Atlantic/South_Georgia""Africa/Accra"
"America/Chicago"
"Europe/London"
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 example, 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(String id : ids) {
System.out.println(id);
}
Be prepared for a lot of output though. There are well more 500 time zone IDs.
The calendar created from a TimeZone object has the default locale. If you want to specify the locale ex-
plicitly, you have 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 creates 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, you can pass it to the setTime() method for a GregorianCalendar
object to set it to the time specified by the Date object:
GregorianCalendar calendar = new GregorianCalendar();
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 you have 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 1995
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 because 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 are not changed. They remain at whatever
Search WWH ::




Custom Search