Java Reference
In-Depth Information
} catch(java.text.ParseException e) {
System.out.println(e);
}
This works because the string is what would be produced by the locale and style. If you omit the day
from the string, or you use the
LONG
style or a different locale, a
ParseException
is thrown.
Gregorian Calendars
The Gregorian calendar is the calendar generally in use today in the western world and is represented by an
object of the
GregorianCalendar
class. A
GregorianCalendar
object encapsulates time zone information,
as well as date and time data. You have no less than seven constructors for
GregorianCalendar
objects,
from the default that creates a calendar with the current date and time in the default locale for your machine
through to a constructor specifying the year, month, day, hour, minute, and second. The default suits most
situations:
GregorianCalendar calendar = new GregorianCalendar();
This object is set to the current instant in time, and you can access this as a
Date
object by calling its
getTime()
:
Date now = calendar.getTime();
You can create a
GregorianCalendar
object encapsulating a specific date and/or time with any of the
following constructors:
GregorianCalendar(int year, int month, int day)
GregorianCalendar(int year, int month, int day, int hour, int minute)
GregorianCalendar(int year, int month, int day, int hour, int minute, int second)
The
day
argument is the day within the month, so the value can be from 1 to 28, 29, 30, or 31, depending
on the month and whether it's a leap year or not. The
month
value is zero-based so January is 0 and Decem-
ber is 11.
The
GregorianCalendar
class is derived from the abstract
Calendar
class from which it inherits a large
number of methods and static constants for use with these methods. The constants include month values
with the names
JANUARY
to
DECEMBER
so you could create a calendar object with the statement:
GregorianCalendar calendar = new GregorianCalendar(1967, Calendar.MARCH, 10);
If you statically import the constant members of the
GregorianCalendar
class you are able to use con-
stants such as
MARCH
and
DECEMBER
without the need to qualify them with the class name. The time zone
and locale is the default for the computer on which this statement executes. If you want to specify a time
zone, there is a
GregorianCalendar
constructor that accepts an argument of type
java.util.TimeZone
.
You can get the default
TimeZone
object by calling the static
getDefault()
method, but if you are going
to the trouble of specifying a time zone, you probably want something other than the default. To create a
particular time zone you need to know its ID. This is a string specifying a region or country plus a location.
For example, here are some examples of time zone IDs:
"Europe/Stockholm"
"Asia/Novosibirsk"