Java Reference
In-Depth Information
A Date object works with a 1900-based year. When you call the setYear() method of this object to set the year
as 2012, you will need to pass 112 (2012 - 1900 = 112). Its getYear() method returns 112 for the year 2012. Months in
this class range from 0 to 11 where January is 0, February is 2 . . . and December is 11.
The Calendar Class
Calendar is an abstract class. An abstract class cannot be instantiated. I will discuss abstract classes in detail in the
chapter on inheritance. The GregorianCalendar class is a concrete class, which inherits the Calendar class.
The Calendar class declares some final static fields to represent date fields. For example, Calendar.JANUARY can
be used to specify the January month in a date. The GregorianCalendar class has a default constructor, which create
an object to represent the current datetime. You can also create a GregorianCalendar object to represent a specific
date using its other constructors. It also lets you obtain the current date in a particular time zone.
// Get the current date in the system default time zone
GregorianCalendar currentDate = new GregorianCalendar();
// Get GregorianCalendar object representing March 26, 2003 06:30:45 AM
GregorianCalendar someDate = new GregorianCalendar(2003, Calendar.MARCH, 26, 6, 30, 45);
// Get Indian time zone, which is GMT+05:30
TimeZone indianTZ = TimeZone.getTimeZone("GMT+05:30");
// Get current date in India
GregorianCalendar indianDate = new GregorianCalendar(indianTZ);
// Get Moscow time zone, which is GMT+03:00
TimeZone moscowTZ = TimeZone.getTimeZone("GMT+03:00");
// Get current date in Moscow
GregorianCalendar moscowDate = new GregorianCalendar(moscowTZ);
Tip
a Date contains a datetime. a GregorianCalendar contains a datetime with a time zone.
The month part of a date ranges from 0 to 11. That is, January is 0, February is 1, and so on. It is easier to use the
constants declared for months and the other date fields in the Calendar class rather than using their integer values.
For example, you should use Calendar.JANUARY constant to represent the January month in your program instead of a 0.
You can get the value of a field in a datetime using the get() method by passing the requested field as an argument.
// Create a GregorianCalendar object
GregorianCalendar gc = new GregorianCalendar();
// year will contain the current year value
int year = gc.get(Calendar.YEAR);
// month will contain the current month value
int month = gc.get(Calendar.MONTH);
 
 
Search WWH ::




Custom Search