File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes GregorianCalendar Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "GregorianCalendar " Watch "GregorianCalendar " New topic


nikil shar
Ranch Hand

Joined: May 25, 2008
Posts: 116
hi all,
have come across this code written by someone else and i dont understand the "gregoriancalendar.get()" part. How can a calender date be deduced from "get(1), get(2), get(5)" ??

I have looked up the API but i dont understand how get(5) can return date/time from default timezone/locale.

Christophe Verré

Joined: Nov 24, 2005
Posts: 14688

If you look at the GregorianCalendar API, you'll see that this class inherits a get(int) method from its Calendar parent. The int variable is a Calendar field, declared in static variables in the Calendar class. For example, static int MONTH, static int YEAR. These are static variables, with a value assigned to it. YEAR happens to be 1, MONTH 2, DAY_OF_MONTH 5 (check them here). By retrieving the yar, month and day, you can make a new calendar, the way it's done above. BUT.... never do it like this. Use Calendar.YEAR, Calendar.MONTH and other declared variables, not their values.

[My Blog]
All roads lead to JavaRanch
Ireneusz Kordal
Ranch Hand

Joined: Jun 21, 2008
Posts: 423
nikil shar wrote:
I have looked up the API but i dont understand how get(5) can return date/time from default timezone/locale.

get(5) doesn't return date/time, it returns day of month.
Look at the source code here:

constants DATE (value 5) is synonym for DAY_OF_MONTH.

And this invocation:
new GregorianCalendar(gregoriancalendar.get(1), gregoriancalendar.get(2), gregoriancalendar.get(5));

is simply: new GregorianCalendar( year, month, day )
David Newton

Joined: Sep 29, 2008
Posts: 12617

Don't even need to look in the source; it's in the Javadocs.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15092

nikil shar wrote:

This code is ugly for several reasons.

First of all, it's not a good idea to use numbers directly when calling the get() method - it makes it impossible to understand immediately what happens by just looking at the source code. Instead of using numbers, use the constants defined in class Calendar, for example:

Second, you should normally not use class GregorianCalendar directly.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: GregorianCalendar
It's not a secret anymore!