Getting current Year and Month resulting strange results

Yaqub Ahmad picture Yaqub Ahmad · Apr 15, 2012 · Viewed 60.7k times · Source

I am working on a learning project related to Android. I am trying to get current year & month by using below code but it not works for me.

GregorianCalendar gc = new GregorianCalendar();
gc.YEAR // returning 1       
gc.MONTH // returning 2

Calendar c = Calendar.getInstance();
c.YEAR // returning 1       
c.MONTH // returning 2

Can someone help me? Am i doing something wrong? please forgive me i am new to java development. thanks.

Answer

Jon Skeet picture Jon Skeet · Apr 15, 2012

Just to give a bit more background:

Both new GregorianCalendar() and Calendar.getInstance() will correctly give a calendar initialized at the current date and time.

MONTH and YEAR are constants within the Calendar class. You should not use them "via" a reference which makes it look like they're part of the state of an object. It's an unfortunate part of the design of the Calendar class that to access the values of different fields, you need to call get with a field number, specified as one of those constants, as shown in other answers:

Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);

Note that the month numbers are 0-based, so at the time of this writing (in April) the month number will be 3.

It's an unfortunate part of the design of the Java language that you can reference static members (such as constants) via expressions of that type, rather than only through the type name.

My recommendations:

  • If your IDE allows it (as Eclipse does), make expressions such as c.YEAR give a compile-time error - you'll end up with much clearer code if you always use Calendar.YEAR.
  • Where possible, use Joda Time - a much better date/time library for Java. Admittedly on Android you may be a bit space-constrained, but if your app does a lot of date/time manipulation, it would save you a lot of headaches.