Getting current Year and Month resulting strange results
Note MONTHS starts from 0..So if you need to map it to practical problems just add +1
int month=c.get(Calendar.MONTH)+1;
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 useCalendar.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.