Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

GregorianCalendar

 
nikil shar
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

ta.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ireneusz Kordal
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: http://www.docjar.com/html/api/java/util/Calendar.java.html

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
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't even need to look in the source; it's in the Javadocs.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15214
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic