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.
Just to give a bit more background:
Both
new GregorianCalendar()andCalendar.getInstance()will correctly give a calendar initialized at the current date and time.MONTHandYEARare constants within theCalendarclass. 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 theCalendarclass that to access the values of different fields, you need to callgetwith a field number, specified as one of those constants, as shown in other answers: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:
c.YEARgive a compile-time error – you’ll end up with much clearer code if you always useCalendar.YEAR.